如何避免内联匿名类声明的合成访问编译器警告,它是什么意思?
我有以下代码:
public class SomeClass {
//InterfaceUpdateListener is an interface
private InterfaceUpdateListener listener = new InterfaceUpdateListener(){
public void onUpdate() {
SomeClass.this.someMethod(); //complier complains on this line of code
}
};
private void someMethod() {
//do something in here on an update event occuring
}
//other code to register the listener with another class...
}
我在 Eclipse 中的编译器抱怨说
从类型 SomeClass 访问封闭方法“someMethod”是由合成访问器方法模拟的。
任何人都可以准确解释
- 这意味着什么,
- 如果我保持原样,可能的后果可能意味着什么(因为它只是一个警告),以及
- 我如何解决它?
谢谢
I have the following code:
public class SomeClass {
//InterfaceUpdateListener is an interface
private InterfaceUpdateListener listener = new InterfaceUpdateListener(){
public void onUpdate() {
SomeClass.this.someMethod(); //complier complains on this line of code
}
};
private void someMethod() {
//do something in here on an update event occuring
}
//other code to register the listener with another class...
}
My compiler in Eclipse complains that
Access to enclosing method 'someMethod' from type SomeClass is emulated by a synthetic accessor method.
Can anyone explain exactly
- what this means,
- what the possible ramifications might mean if I leave it as is (since its only a warning), and
- how I might fix it?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我只是停用该规则(即使编译器不为此生成警告)。如果构造是合法的,并且编译器添加了额外的方法来支持它,那么它就必须这样做。
我怀疑这种合成方法会造成性能的显着损失。如果有必要,JIT 无论如何都必须内联它。
I would just deactivate the rule (i.e. make the compiler not generate warning for this). If the construction is legal, and if an additional method is added by the compiler to support it, then it's the way it must be done.
I doubt there is a significant loss of performance caused by this synthetic method. The JIT must inline it anyway if necessary.
这个怎么样?
只有一个类声明必须由 JVM (PermGen) 保存,实现类在 SomeClass 之外仍然不可用(我认为这是编写嵌套类的唯一合法意图),最后但并非最不重要的一点是您还可以提供以 InterfaceUpdateListener 作为参数的第二个构造函数(如果需要更多灵活性和可测试性)。并且无需更改警告。
提供了expect
,SomeClass可能会像这样实现
How about this?
There's only one class declaration that has to be keept by your JVM (PermGen), implementing class is still not available outside SomeClass (I think this is the only legal intention to write an nested class anyway) and last but not least you might also provide a second constructor with InterfaceUpdateListener as argument (if needed for mor flexibility and testability). And ther's no need to change warnings.
expect
is provided, SomeClass might be implemented like this