Get field of a class object and set or get its value
import java.lang.reflect.Field;
import java.util.Date;
public class Main {
public static void main(String[] args) throws Exception {
Bean demo = new Bean();
Class clazz = demo.getClass();
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);
}
}
class Bean {
public static Date now;
public Long id;
public String name;
}
Related examples in the same category