在Java中,当我不在内部类时,如何访问外部类? [英] In Java, how do I access the outer class when I'm not in the inner class?

查看:111
本文介绍了在Java中,当我不在内部类时,如何访问外部类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个内部类的实例,如何从不在内部类中的代码访问外部类?我知道在内部类中,我可以使用 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; }
  }
}


推荐答案

外部$ Inner 类的字节码将包含一个名为的包格式字段,此字段为 C>外。这就是用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆