我有一個int,short,byte或long類型的對象,我需要給它一個新的值。這在Java中可能嗎?如果是的話,怎麼樣?Java反射〜設置原始類型的內部對象值
public static void set(Object obj, int value) throws Exception
{
Class<?> c = obj.getClass();
if (c.equals(Integer.class))
{
// ???
}
}
我有一個int,short,byte或long類型的對象,我需要給它一個新的值。這在Java中可能嗎?如果是的話,怎麼樣?Java反射〜設置原始類型的內部對象值
public static void set(Object obj, int value) throws Exception
{
Class<?> c = obj.getClass();
if (c.equals(Integer.class))
{
// ???
}
}
整數是不可變的。您不能將值設置爲Integer
實例。
同樣,基元類型的其他包裝類也是不可變的。
恩,謝謝!這解決了我的麻煩。我將不得不繞過場地。 – Bitterblue 2013-04-10 15:08:25
不客氣。是的,你必須通過字段來設置它,或者引入一個包裝器對象。 – gaborsch 2013-04-10 15:12:05
是的,只要你知道你在處理什麼樣的原始類型。
Class clazz = Class.forName("TheClass");
Field f = clazz.getDeclaredField("ThePrimitiveField");
Object obj;
f.setBoolean(obj, true);
這將改變obj的「ThePrimitiveField」字段。如果你不知道類型...
Field f;
Object obj;
try {
f.setBoolean(obj, true);
} catch (IllegalArgumentException ex) {
try {
f.setByte(obj, 16);
} catch (IllegalArgumentException ex) {
try {
f.setChar(obj, 'a');
// etc
}
}
}
如果你知道類型做到這一點:
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));
}
是的謝謝!這是我的計劃B.我在這裏問過,因爲我不想改變計劃A的代碼。^^ – Bitterblue 2013-04-10 15:30:52
是否要將值設置爲* obj instance *,或者要設置對象的*屬性*? – gaborsch 2013-04-10 15:01:34
@GaborSch obj是一個整數,所以我想設置它的值。 – Bitterblue 2013-04-10 15:13:46
你想int或整數?雖然不能修改包裝類,但可以將整數設置爲新值。檢查我的答案的底部的例子,這樣做。 – TofuBeer 2013-04-10 15:16:04