您需要执行此操作的事实表明设计存在缺陷。
但是,可以按照以下步骤进行操作:
class A{ private int privateField = 3;}class B extends A{}class C extends B{ void m() throws NoSuchFieldException, IllegalAccessException { Field f = getClass().getSuperclass().getSuperclass().getDeclaredField("privateField"); f.setAccessible(true); // enables access to private variables System.out.println(f.get(this)); }}致电:
new C().m();
Andrzej Doyle所说的 “提高类层次结构”的 一种方法如下:
Class c = getClass();Field f = null;while (f == null && c != null) // stop when we got field or reached top of class hierarchy{ try { f = c.getDeclaredField("privateField"); } catch (NoSuchFieldException e) { // only get super-class when we couldn't find field c = c.getSuperclass(); }}if (f == null) // walked to the top of class hierarchy without finding field{ System.out.println("No such field found!");}else{ f.setAccessible(true); System.out.println(f.get(this));}


