在构造函数警告中泄漏这个 [英] Leaking this in constructor warning

查看:28
本文介绍了在构造函数警告中泄漏这个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想避免 Netbeans 6.9.1 的(大部分)警告,并且我对 'Leaking this in constructor' 警告有问题.

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.

我理解这个问题,在构造函数中调用方法并传递this"是危险的,因为this"可能尚未完全初始化.

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.

旧代码(简化):

private Singleton() {
  ...
  addWindowFocusListener(this);
}

public static Singleton getInstance() {

  ...
  instance = new Singleton();
  ...
}

新代码(简化):

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);
  }

}

当然,我想要一个不需要修改我使用这个类的所有代码的修复程序(例如通过调用 init 方法).

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).

推荐答案

既然你确保把你的 instances.add(this) 放在构造函数的末尾,你应该恕我直言安全地告诉编译器简单地取消警告 (*).就其性质而言,警告并不一定意味着出现问题,它只是需要您注意.

Since you make sure to put your instances.add(this) at the end of the constructor you should IMHO be safe to tell the compiler to simply suppress the warning (*). A warning, by its nature, doesn't necessarily mean that there's something wrong, it just requires your attention.

如果您知道自己在做什么,可以使用 @SuppressWarnings 注释.就像 Terrel 在他的评论中提到的那样,以下注释从 NetBeans 6.9.1 开始:

If you know what you're doing you can use a @SuppressWarnings annotation. Like Terrel mentioned in his comments, the following annotation does it as of NetBeans 6.9.1:

@SuppressWarnings("LeakingThisInConstructor")

(*) 更新: 正如 Isthar 和 Sergey 指出的那样,在某些情况下,泄漏"构造函数代码看起来非常安全(如您的问题),但事实并非如此.是否有更多的读者可以认可这一点?由于上述原因,我正在考虑删除此答案.

(*) Update: As Isthar and Sergey pointed out there are cases where "leaking" constructor code can look perfectly safe (as in your question) and yet it is not. Are there more readers that can approve this? I am considering deleting this answer for the mentioned reasons.

这篇关于在构造函数警告中泄漏这个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆