从内部类对象获取外部类对象 [英] Getting hold of the outer class object from the inner class object

查看:60
本文介绍了从内部类对象获取外部类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码.我想获取外部类对象,我使用它创建了内部类对象 inner.我该怎么做?

I have the following code. I want to get hold of the outer class object using which I created the inner class object inner. How can I do it?

public class OuterClass {

    public class InnerClass {
        private String name = "Peakit";
    }

    public static void main(String[] args) {
        OuterClass outer = new OuterClass();
        InnerClass inner = outer.new InnerClass();
       // How to get the same outer object which created the inner object back?
        OuterClass anotherOuter = ?? ;

        if(anotherOuter == outer) {
             System.out.println("Was able to reach out to the outer object via inner !!");
        } else {
             System.out.println("No luck :-( ");
        }
    }
}

嗯,你们中的一些人建议通过添加一个方法来修改内部类:

Well, some of you guys suggested of modifying the inner class by adding a method:

public OuterClass outer() {
   return OuterClass.this;
}

但是如果我没有控制权去修改内部类,那么(只是为了确认)我们有没有其他方式从内部类对象中获取对应的外部类对象?

But what if I don't have control to modify the inner class, then (just to confirm) do we have some other way of getting the corresponding outer class object from the inner class object?

推荐答案

在内部类本身内,您可以使用 OuterClass.this.这个表达式允许引用任何词法封闭实例,在 JLS 中被描述为 合格的this.

Within the inner class itself, you can use OuterClass.this. This expression, which allows to refer to any lexically enclosing instance, is described in the JLS as Qualified this.

我不认为有一种方法可以从内部类的代码之外获取实例.当然,你可以随时介绍自己的财产:

I don't think there's a way to get the instance from outside the code of the inner class though. Of course, you can always introduce your own property:

public OuterClass getOuter() {
    return OuterClass.this;
}

通过实验,看起来保存对外部类的引用的字段具有包级访问权限 - 至少对于我正在使用的 JDK.

By experimentation, it looks like the field holding the reference to the outer class has package level access - at least with the JDK I'm using.

使用的名称 (this$0) 在 Java 中实际上有效,尽管 JLS 不鼓励使用:

The name used (this$0) is actually valid in Java, although the JLS discourages its use:

$ 字符只能用于机械生成的源代码或,很少,访问预先存在的名称遗留系统.

The $ character should be used only in mechanically generated source code or, rarely, to access pre-existing names on legacy systems.

这篇关于从内部类对象获取外部类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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