我想避免(大多数)Netbeans 6.9.1的警告,我的'Leaking this in constructor'警告有问题.
我理解这个问题,在构造函数中调用一个方法并传递" this"是危险的,因为" this"可能没有完全初始化.
很容易在我的单例类中修复警告,因为构造函数是私有的,只能从同一个类中调用.
旧代码(简化):
private Singleton() {
...
addWindowFocusListener(this);
}
public static Singleton getInstance() {
...
instance = new Singleton();
...
}
Run Code Online (Sandbox Code Playgroud)
新代码(简化):
private Singleton() {
...
}
public static Singleton getInstance() {
...
instance = new Singleton();
addWindowFocusListener( instance );
...
}
Run Code Online (Sandbox Code Playgroud)
如果构造函数是公共的并且可以从其他类调用,则此修复不起作用.如何修复以下代码:
public class MyClass {
...
List<MyClass> instances = new ArrayList<MyClass>();
...
public MyClass() {
...
instances.add(this);
}
}
Run Code Online (Sandbox Code Playgroud)
当然我想要一个修复,它不需要使用这个类修改我的所有代码(例如通过调用init方法).