使用java Reflection更改对象的字段值,即int

时间:2014-06-02 07:25:38

标签: java reflection

我有一个包含3个字段的表,name = varchar,number1 = int,number2 = int

下面我可以一次修改一个字段。 我怎么能一次更改int类型的所有字段?

public static void change(Object t) throws IllegalArgumentException,
IllegalAccessException {
    Class c = t.getClass(); 
    Field f = t.getDeclaredFields()[0];
    f.set(o, "name2");
    int a = f.getModifiers();
    System.out.println(Modifier.isVolatile(a));
    Field f2 = t.getDeclaredFields()[1];
    f2.setInt(t, 10);
    int a2 = f2.getModifiers();
    System.out.println(Modifier.isVolatile(a2));
}

我想遵循的步骤是检查字段是否为int,然后分配值10将它们全部修复。惠特java反映。

自动获取第二个和第三个字段,

我试试这个

public static void sta(Object t) throws IllegalArgumentException, IllegalAccessException {
Class<?> c = t.getClass();
for (Field f : t.getDeclaredFields()) {
    if (f.getType() == int.class) {
        f.setAccessible(true);
        f.set(t, 10);
    }
}


test.java

public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException {
    Object t = new Object("Name1", 777, 777);


    teste2.sta(t);
System.out.println(t.number1);

}}

Object.java

public class Object {
String name;
int number1;
    int number2;
public Object(String name, int number1, int number2){
    this.name=name;
    this.numeber1=number1;
            this.number2=number2 ;
}
public String getName(){
    return name;
}
public int getNumber1(){
    return number1;
}
public int getNumber2(){
    return number2;
    }
}

错误是

Exception in thread "main" java.lang.IllegalArgumentException: Can not set java.lang.String field Object.name to java.lang.Integer
    at  un.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:164)   at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:164)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:164)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:168)
    at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81)
    at java.lang.reflect.Field.set(Field.java:741)
    at teste2.sta(teste2.java:76)
    at teste2.main(teste2.java:95)
Java Result: 1

如何获取System.out.println(t.number1)的输出;通过方法teste2.sta(t);

修改值
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException {
        Object t = new Object("Name1", 777, 777);


        teste2.sta(t);
    System.out.println(t.number1);

    }}

1 个答案:

答案 0 :(得分:2)

以下代码遍历在给定对象obj的具体类中直接声明的所有int字段,并将它们全部设置为10:

Class<?> c = obj.getClass();
for (Field f : c.getDeclaredFields()) {
    if (f.getType() == int.class) {
        f.setAccessible(true);
        f.set(obj, 10);
    }
}