黑马程序员技术交流社区
标题:
你猜猜这样做会怎么样?
[打印本页]
作者:
Mr_Unhappy
时间:
2014-9-14 16:06
标题:
你猜猜这样做会怎么样?
package FieldDemo;
import java.lang.reflect.Field;
public class FieldTest {
public static void main(String[] args)
throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, ClassNotFoundException {
Test test = new Test("li","wu");
Field testX = test.getClass().getField("x");
System.out.println(testX.get(test));
//暴力反射
Field testY = Class.forName("FieldDemo.Test").getDeclaredField("y");
//设置y为可见
testY.setAccessible(true);
System.out.println(testY.get(test));
}
}
class Test{
public String x;
private String y;
public Test(String x, String y) {
super();
this.x = x;
this.y = y;
}
}
复制代码
在此处,是通过new Test对象来得到Test类对应的Class对象,你有没有试过,用其他两种方式来得到Test类对应的Class对象?你猜猜,用其他两种方式会不会成立,结果会吓你一大跳的{:2_40:}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2