[英]Using “this” in the constructor of a final class
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. 当我这样做时,NetBeans抱怨在构造函数中使用
this
。 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. 好吧,我明白了,在一般情况下这是一种危险的做法,因为有人可以扩展我的类,然后我会泄漏
this
指的是一个未完全初始化的对象。 I didn't want to turn off this warning, so I thought that I could make the class final
. 我不想关掉这个警告,所以我想我可以让这个班级
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. 这样,没有人会能够延长我的课,因此它应该是相当安全的使用
this
,作为初始化完成,因为这一点。 But NetBeans still shows the warning even if I mark the inner class as final
. 但即使我将内部类标记为
final
NetBeans仍会显示警告。
Am I right or is there something I missed? 我是对的还是我错过了什么? Is it just NetBeans being too picky?
它只是NetBeans过于挑剔吗? Besides possible multi-threading memory model issues I can't think of any dangers of such
this
usage. 除了可能的多线程内存模型问题,我想不出
this
用法的任何危险。
It's a Netbeans-specific warning. 这是一个特定于Netbeans的警告。 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. 这段代码有问题,我不应该忽略“在构造函数中泄漏”警告。
Leaking this in constructor warning has a discussion of this Netbeans warning. 在构造函数警告中泄漏此问题已讨论此Netbeans警告。
If pendingTasksByKey
has a corresponding remove
somewhere during the life cycle of these classes I'd say you are right, Netbeans is being picky. 如果
pendingTasksByKey
在这些类的生命周期中的某个地方有相应的remove
,我会说你是对的,Netbeans很挑剔。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.