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