[英]How to access local variables in anonymous inner actionListener class and actionPerformed method?
[英]Anonymous Class Accesing Local Variables
如果您查看下面的代码,您会看到我在方法 M() 中声明了 int x = 0。 然后我在所述方法中声明一个匿名类并声明 int z = x。 我的问题是我虽然这是不允许的,因为 x 是在匿名类存在的封装方法中定义的,而不是常量。 也许我误解了一些东西。 有人可以帮助清除我的困惑吗?
public class SomeClass {
public void someMethod(Super pObj) {}
}
public class Super {
public Super() {}
public void aMethod() {}
}
public class SubClass extends Super {
public void M() {
SomeClass someObject = new SomeClass();
int x = 0;
someObject.someMethod(new Super() {
int z = x;
@Override public void aMethod() {}
});
}
}
x
变量实际上是final ,因此可以在匿名类中使用(从 Java SE 8 开始)。
有关其他信息,您可以查看此线程
我还使用了解决方法女巫包装器最终对象。 这样,对象实际上是最终的,但您可以更改其中的值。
final Counter counter = new Counter() ; 在匿名课程中,您可以执行以下操作:计数器。 增加值() ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.