那是因为,你把主函数和私有的y放在同一个类中了,
在同一个类中,私有成员是可以访问的,你把它们分到不同类中就有区别了。
代码在下边,你把false改为true就可以执行了
- import java.lang.reflect.Field;
- class InstanceDemo {
- public int x;
- private int y;
- public InstanceDemo (int x, int y) {
- super();
- this.x = x;
- this.y = y;
- }
- }
- public class Demo {
-
- public int x;
- private int y;
- public Demo(int x, int y) {
- super();
- this.x = x;
- this.y = y;
- }
- public static void main(String[] args) throws Exception {
- // Field y = InstanceDemo.class.getField("x");
- // Field x = InstanceDemo.class.getDeclaredField("y");
- InstanceDemo i = new InstanceDemo (5, 10);
- Field fieldY = i.getClass().getDeclaredField("y");
- fieldY.setAccessible(false);
- System.out.println(fieldY.get(i));
- }
- }
复制代码 |