【发布时间】:2011-09-26 02:18:46
【问题描述】:
在给定对内部类对象的引用的情况下,如何访问外部类的字段?
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 和许多其他变体。有没有我想要的语法?
【问题讨论】:
-
内部类的目的不是只在其外部类中使用吗?
-
我认为这就是这样做的方法。如果您觉得不对,也许您可以考虑重构或以不同的方式构建这些类?
-
我不知道有什么其他方法可以做到这一点,但我会说,如果你不得不做这样的扭曲,这通常意味着你应该重新考虑设计。
-
@Overbose - 许多内部类实例被传递给世界。例如,许多 Iterator 类是其 Iterable 集合的内部类。内部类有助于减少命名空间混乱(例如,
Float、Arc2D.Float、CubicCurve2D.Float、DataBuffer.Float等)
标签: java field inner-classes