Leaking this in constructor warning has a discussion of this Netbeans warning.
If pendingTasksByKey
has a corresponding remove
somewhere during the life cycle of these classes I'd say you are right, Netbeans is being picky.
문제
I have an inner helper class, and I would like to add each new instance of it to a map in the containing class, like this:
public class SomeService {
private final Map<Integer, ServiceTask> pendingTasksByKey;
private class ServiceTask {
private ServiceTask(int key) {
// initialization...
pendingTasksByKey.put(key, this);
}
}
// the rest of the code follows
}
When I do it, NetBeans complains about using this
in the constructor. OK, I get it, it's a dangerous practice in the general case because someone could extend my class and then I would be leaking this
referring to an incompletely initialized object. I didn't want to turn off this warning, so I thought that I could make the class final
. This way no one would be able to extend my class, and therefore it should be pretty safe to use this
, as the initialization is complete as this point. But NetBeans still shows the warning even if I mark the inner class as final
.
Am I right or is there something I missed? Is it just NetBeans being too picky? Besides possible multi-threading memory model issues I can't think of any dangers of such this
usage.
해결책 2
Leaking this in constructor warning has a discussion of this Netbeans warning.
If pendingTasksByKey
has a corresponding remove
somewhere during the life cycle of these classes I'd say you are right, Netbeans is being picky.
다른 팁
It's a Netbeans-specific warning. It is a reminder that the object is not yet constructed so it could be a problem. If you aren't doing anything where that will be a problem then you can ignore it. For example look at this code:
class A {
public Object obj;
public A() {
B b = new B();
b.addMe(this);
obj = new Object();
}
}
class B {
ArrayList<A> list = new ArrayList<A>(0);
public void addMe(A a) {
list.add(a);
System.out.println(a.obj.toString());
}
}
This code has a problem and I should not ignore the "leaking this in constructor" warning.