I'd like to avoid (most of the) warnings of Netbeans 6.9.1, and I have a problem with the 'Leaking this in constructor'
warning.
I understand the problem, calling a method in the constructor and passing "this
" is dangerous, since "this
" may not have been fully initialized.
It was easy to fix the warning in my singleton classes, because the constructor is private and only called from the same class.
Old code (simplified):
private Singleton() {
...
addWindowFocusListener(this);
}
public static Singleton getInstance() {
...
instance = new Singleton();
...
}
New code (simplified):
private Singleton() {
...
}
public static Singleton getInstance() {
...
instance = new Singleton();
addWindowFocusListener( instance );
...
}
This fix is not working if the constructor is public and can be called from other classes. How is it possible to fix the following code:
public class MyClass {
...
List<MyClass> instances = new ArrayList<MyClass>();
...
public MyClass() {
...
instances.add(this);
}
}
Of course I want a fix which does not require to modify all my codes using this class ( by calling an init method for instance).