Java反射〜设置原始类型的内部对象值

时间:2013-04-10 14:53:35

标签: java reflection integer primitive

我有一个int,short,byte或long类型的对象,我需要给它一个新值。这可能在Java中吗?如果是的话怎么样?

public static void set(Object obj, int value) throws Exception
{
    Class<?> c = obj.getClass();
    if (c.equals(Integer.class))
    {
        // ???
    }
}

3 个答案:

答案 0 :(得分:2)

整数是不可变的。您无法为Integer实例设置值。

类似地,基本类型的其他包装类也是不可变的。

答案 1 :(得分:1)

是的,只要你知道你正在处理什么原始类型。

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
        }
    }
}

答案 2 :(得分:1)

如果您知道类型,请执行以下操作:

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);
    }
}

并且,如果你想使用包装类(Integer,Character等),你可以添加:

else if(type.equals(Integer.class))
{
    field.set(fooA, new Integer(43));
}