Java如何获取类对象的字段并设置或获取其值?
Refection演示程序,用于获取类的对象的字段并设置或获取其值。
package org.nhooo.example.lang;
import java.util.Date;
import java.lang.reflect.Field;
public class GetSetFieldDemo {
public static Date now;
public Long id;
public String name;
public static void main(String[] args) {
GetSetFieldDemo demo = new GetSetFieldDemo();
Class clazz = demo.getClass();
try {
//获取字段ID,设置其值并回读
Field field = clazz.getField("id");
field.set(demo, new Long(10));
Object value = field.get(demo);
System.out.println("Value = " + value);
//获取静态字段日期,设置其值并回读
field = clazz.getField("now");
field.set(null, new Date());
value = field.get(null);
System.out.println("Value = " + value);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短