在给定对内部类对象的引用的情况下,如何访问外部类的字段?
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/