读书人

this$零意义

发布时间: 2012-10-27 10:42:26 作者: rapoo

this$0意义
The bytecode of the Outer$Inner class will contain a package-scoped field named this$0 of type Outer. That's how non-static inner classes are implemented in Java, because at bytecode level there is no concept of an inner class.

You should be able to read that field using reflection, if you really want to. I have never had any need to do it, so it would be best for you to change the design so that it's not needed.

Here is how your example code would look like when using reflection. Man, that's ugly.

public class Outer {
public static void foo(Inner inner) {
try {
Field this$0 = inner.getClass().getDeclaredField("this$0");
Outer outer = (Outer) this$0.get(inner);
System.out.println("The outer class is: " + outer);

} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}

public class Inner {
}

public void callFoo() {
// The constructor of Inner must be called in
// non-static context, inside Outer.
foo(new Inner());
}

public static void main(String[] args) {
new Outer().callFoo();
}
}

参考出处:
http://stackoverflow.com/questions/763543/in-java-how-do-i-access-the-outer-class-when-im-not-in-the-inner-class
http://www.tns.lcs.mit.edu/manuals/java-1.1.1/guide/innerclasses/spec/innerclasses.doc2.html

读书人网 >编程

热点推荐