本帖最后由 yong230 于 2013-1-24 16:19 编辑
可以暴力访问private字段的,看下面:
import java.lang.reflect.Field;
public class RelexFiletest {
/**
* @param args
* @throws ClassNotFoundException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public static void main(String[] args) throws ClassNotFoundException, SecurityException, NoSuchFieldException, InstantiationException, IllegalAccessException {
getFileDemo();
}
public static void getFileDemo() throws ClassNotFoundException, SecurityException, NoSuchFieldException, InstantiationException, IllegalAccessException {
/*
* 获取字节码中的字段
*/
Class clazz=Class.forName("cn.soft.p.bean.People");
Field field=null;//clazz.getField("age");//只获取本类共有字段。
field=clazz.getDeclaredField("age");//可以获取本类私有和共有字段
field.setAccessible(true);//这个是暴力设置private字段可以访问
System.out.println(field);
Object obj=clazz.newInstance();
Object o=field.get(obj);
System.out.println(o);
}
} |