당신은 종류가 이렇게 알고있는 경우 : 당신이 종류를 알 수없는 경우
public class Main
{
public static void main(String[] args)
throws NoSuchFieldException,
IllegalArgumentException,
IllegalAccessException
{
Foo fooA;
Foo fooB;
final Class<?> clazz;
final Field field;
fooA = new Foo();
fooB = new Foo();
clazz = fooA.getClass();
field = clazz.getDeclaredField("bar");
System.out.println(fooA.getBar());
System.out.println(fooB.getBar());
field.setAccessible(true); // have to do this since bar is private
field.set(fooA, 42);
System.out.println(fooA.getBar());
System.out.println(fooB.getBar());
}
}
class Foo
{
private int bar;
public int getBar()
{
return (bar);
}
}
당신이 이런 식으로 뭔가를 할 수 있습니다
public class Main
{
public static void main(String[] args)
throws NoSuchFieldException,
IllegalArgumentException,
IllegalAccessException
{
Foo fooA;
Foo fooB;
final Class<?> clazz;
final Class<?> type;
final Field field;
fooA = new Foo();
fooB = new Foo();
clazz = fooA.getClass();
field = clazz.getDeclaredField("bar");
System.out.println(fooA.getBar());
System.out.println(fooB.getBar());
field.setAccessible(true); // have to do this since bar is private
type = field.getType();
if(type.equals(int.class))
{
field.set(fooA, 42);
}
else if(type.equals(byte.class))
{
field.set(fooA, (byte)1);
}
else if(type.equals(char.class))
{
field.set(fooA, 'A');
}
System.out.println(fooA.getBar());
System.out.println(fooB.getBar());
}
}
class Foo
{
private char bar;
public char getBar()
{
return (bar);
}
}
, 당신은 래퍼 클래스 (정수, 문자 등 ..) 사용하려면이 추가 할 수 있습니다
else if(type.equals(Integer.class))
{
field.set(fooA, new Integer(43));
}
을
* obj instance *에 값을 설정 하시겠습니까, 아니면 객체의 * 속성 *을 설정 하시겠습니까? – gaborsch
@GaborSch obj는 정수이므로 값을 설정하고 싶습니다. – Bitterblue
int 또는 Integer를 원하십니까? 래퍼 클래스를 수정할 수는 없지만 Integer를 새로운 값으로 설정할 수 있습니다. 내 답변의 맨 아래에있는 예를 확인하십시오. – TofuBeer