日期:2014-05-20 浏览次数:20766 次
import java.lang.reflect.*; class AA { private int i= 10; } class BB extends AA { private int i= 8; } class CC extends BB { private int i = 6; } public class Test { public Test() { } public static void main(String[] args) throws Exception{ CC o = new CC(); Class c = o.getClass(); Class b = c.getSuperclass(); Class a = b.getSuperclass(); Field ci = c.getDeclaredField("i"); Field bi = b.getDeclaredField("i"); Field ai = a.getDeclaredField("i"); ci.setAccessible(true); bi.setAccessible(true); ai.setAccessible(true); System.out.println(ci.getInt(o)); System.out.println(bi.getInt(o)); System.out.println(ai.getInt(o)); } }
------解决方案--------------------
对于私有的属性可以采用提供get和set方法去访问