简体   繁体   English

通过内部类引用访问外部类变量

[英]accessing outer class variables via an inner class reference

 public static class Outer {
        public int field;
        public class Inner {}
 }


 //  caller methods
 public static void foo(Outer.Inner inner) {
       // here I want to access the "field"
       // tried the following, none worked
       System.out.println(inner.Outer.field);
       System.out.println(inner.Outer.this.field);
 }

How do I access a non-static fields of a class from a reference of its non-static inner class in Java? 如何从Java中非静态内部类的引用访问该类的非静态字段?

PS 聚苯乙烯
People kept saying it's bad design. 人们一直说这是不好的设计。 Yes, I agree 100% this is bad "design". 是的,我同意100%这是不好的“设计”。 At least, it's bad for code that needs to be read by humans. 至少,这对需要人类阅读的代码不利。 But if this is for generated code, I think I'll get a pass. 但是,如果这是用于生成的代码,我想我会通过的。 (have anyone tried reading code that comes out of Antlr, for eg?) (有没有人尝试读取过Antlr的代码,例如?)

Seems like a not-too-good idea, but anyway, you'll need to explicitly export it yourself. 似乎不太好主意,但是无论如何,您都需要自己明确导出它。

public static class Outer {
    public int field;
    public class Inner {
        public Outer outer() {
            return Outer.this;
        }
    }
}

//  caller methods
public static void foo(Outer.Inner inner) {
   System.out.println(inner.outer().field);
}

This could work - bad coding practice anyway 这可能有效-仍然是不良的编码实践

 public static class Outer {
        public int field;
        public class Inner {
            public Outer outer=Outer.this
        }
 }


 //  caller methods
 public static void foo(Outer.Inner inner) {
       System.out.println(inner.Outer.field);
       System.out.println(inner.Outer.this.field);
 }

One option is mentioned in the other answers. 在其他答案中提到了一个选项。 If for some reason it doesn't fit your case, you can expose field from Inner, with getter (and setter if you need to): 如果由于某种原因它不适合您的情况,则可以使用getter(如果需要,可以使用setter)从Inner公开field

public Outer class {
    private int field;
    public class Inner {
        public int getOuterField() {
            return field;
        }
    }
}

A different approach would to be pass the corresponding Outer instance wherever you need to use Inner , so foo will take two arguments in this case. 无论何时需要使用Inner ,都可以通过不同的方法传递相应的Outer实例,因此foo在这种情况下将接受两个参数。

And yeah, I agree with all the comments posted - all of the options indicate bad design. 是的,我同意所有已发表的评论-所有选项均表示设计不良。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM