java - 访问外部类的字段

标签 java field inner-classes

在给定对内部类对象的引用的情况下,如何访问外部类的字段?

class Outer
{
    int field;

    class Inner
    {
        void method(Inner parameter)
        {
            // working on the current instance is easy :)
            field = 0;
            Outer.this.field = 1;

            // working on another instance is hard :(
            parameter.field = 2;              // does not compile
            parameter.Outer.this.field = 3;   // does not compile
            parameter.outer().field = 4;      // This works...
        }

        // ...but I really don't want to have to write this method!
        Outer outer()
        {
            return Outer.this;
        }
    }
}

我还尝试了 Outer.parameter.field 和许多其他变体。是否有一种语法可以满足我的要求?

最佳答案

这个解决方案怎么样:

class Outer
{
    int field;

    class Inner
    {
        final Outer outer = Outer.this;
        void method(Inner parameter)
        {
            // working on the current instance is easy :)
            field = 0;
            Outer.this.field = 1;

            // working on another instance:
            parameter.outer.field = 2; 
        }
    }
}

关于java - 访问外部类的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6537082/

相关文章:

flutter - 有没有办法在 dart 中实现内部类?

c - 需要在 C 中获取结构与其字段之一之间的偏移量

MySQL ORDER BY Column = value AND distinct?

java - 在 Java 中,类的方法冗余地返回类的修改后的全局字段是一种好的做法吗?

java - 执行 com.android.build.gradle.internal.tasks.FinalizeBundleTask$BundleToolRunnable 时发生故障

Java,导入未解析,继承,内部类

c++ - 类中枚举类的运算符重载

java - 使用 Jersey 和 Jackson 序列化(延迟加载)实体

java - Maven 构建依赖项失败

java - 使用javax.mail发送大电子邮件,某些电子邮件发送失败