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

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

问题描述

我想避免(大多数)Netbeans 6.9.1的警告,我有一个问题'在构造函数中泄漏'警告。

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 是危险的,因为可能尚未完全初始化。

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

如果构造函数是public,可以从其他类调用。如何修复以下代码:

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天全站免登陆