解决容易出错的ConstructorLeaks对调用其他构造函数的构造函数的此警告

时间:2018-01-02 01:32:02

标签: java constructor errorprone

我们有一些类用于共享构造函数逻辑的通常模式:

public X(E... processors)
{
    this(ImmutableList.copyOf(processors));
}

public X(Collection<E> processors)
{
    this.processors = ImmutableList.copyOf(processors);
}

在这种情况下,容易出错的人抱怨ConstructorLeaksThis

.../X.java:61: error: [ConstructorLeaksThis] Constructors should not pass the 'this' reference out in method invocations, since the object may not be fully constructed.
        this(ImmutableList.copyOf(processors));
        ^
    (see http://errorprone.info/bugpattern/ConstructorLeaksThis)

如果这个实现模式实际上不安全,我相信它可以很容易地重构为静态方法,但我想问题是, 是不安全的?也许这不是编译器检查要检测的内容?

2 个答案:

答案 0 :(得分:2)

Error-prone定义了ConstructorLeaksThis问题:

  

在执行构造函数期间,创建新构造函数是危险的   其他代码可访问的实例。实例的字段,包括   最终字段,可能尚未初始化,并且正在执行实例   方法可能会产生意想不到的结果。

...从您的代码中,您没有违反规则,Java文档也写了Using this with a Constructor,这是误报,同样的问题报告here

顺便说一句,您可以在构造函数中添加@SuppressWarnings("ConstructorLeaksThis")来抑制错误或重构您的代码而不使用@SuppressWarnings来防止隐藏的错误。

答案 1 :(得分:1)

我很确定这是一个错误。

通常,此错误意味着您将引用传递给当前未构造的对象,即someList.add(this)

然而构造函数链接非常好,通常是一种很好的做法。

相关问题