创建一个类ReflectPoint.java:
package com.hubin.classes;
public class ReflectPoint {
public int x=2345;
private int y;
private String str1="hello";
public String getStr1() {
return str1;
}
private String str2="yelow";
private String str3="binbin";
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
public ReflectPoint() {
super();
}
}
创建另一个ReflectPointTest.java类:
package com.hubin.classes;
import java.lang.reflect.Field;
public class ReflectPointTest {
public static void main(String []args) throws Exception{
ReflectPoint rp=new ReflectPoint();
setSomeFields(rp);
System.out.println(rp.getStr1());
}
private static void setSomeFields(ReflectPoint rp) throws Exception{
// TODO Auto-generated method stub
//获得ReflectPoint类中的一个属性str1
Field field=rp.getClass().getDeclaredField("str1");
//强制获取属性中的值(私有属性不能轻易获取其值)
field.setAccessible(true);
System.out.println(field.get(rp));
//修改属性的值
field.set(rp, "123456789");
}
private static void getAllFields(ReflectPoint rp) throws Exception{
// TODO Auto-generated method stub
Field []fields=rp.getClass().getDeclaredFields();
for(Field field:fields){
field.setAccessible(true);
System.out.println(field.get(rp));
}
}
}