在Java中,当我不在内部类时如何访问外部类? [英] In Java, how do I access the outer class when I'm not in the inner class?
问题描述
如果我有一个内部类的实例,我怎样才能从不在内部类中的代码访问外部类?我知道在内部类中,我可以使用 Outer.this
来获取外部类,但是我找不到任何外部获取方式.
If I have an instance of an inner class, how can I access the outer class from code that is not in the inner class? I know that within the inner class, I can use Outer.this
to get the outer class, but I can't find any external way of getting this.
例如:
public class Outer {
public static void foo(Inner inner) {
//Question: How could I write the following line without
// having to create the getOuter() method?
System.out.println("The outer class is: " + inner.getOuter());
}
public class Inner {
public Outer getOuter() { return Outer.this; }
}
}
推荐答案
Outer$Inner
类的字节码将包含一个名为 this$0
的包范围字段输入 Outer
.这就是非静态内部类在 Java 中的实现方式,因为在字节码级别没有内部类的概念.
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();
}
}
这篇关于在Java中,当我不在内部类时如何访问外部类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!