- 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:} |
|