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 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志