解决容易出错的 ConstructorLeaksThis warning on constructors which call other constructors

Resolving error-prone ConstructorLeaksThis warning on constructors which call other constructors

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

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)

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

Error-prone defines ConstructorLeaksThis 问题:

During the execution of a constructor, it’s dangerous to make the new instance accessible to other code. Fields of the instance, including final fields, may not yet be initialized, and executing instance methods may yield unexpected results.

...从您的代码来看,您没有违反规则,Java 文档也写了关于 Using this with a Constructor, it's a false positive, the same issue was reported here

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

我很确定这是一个错误。

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

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