java - 解决调用其他构造函数的构造函数上容易出错的 ConstructorLeaksThis 警告

标签 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)

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

最佳答案

Error-prone定义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 ,这是误报,报告了同样的问题 here

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

关于java - 解决调用其他构造函数的构造函数上容易出错的 ConstructorLeaksThis 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48054634/

相关文章:

java - 如何访问存储库中 LiveData 模型的值

java - 在单个节点中运行 Spark 计算

c++ - 在构造函数初始化列表中使用结构 vector 初始化类结构

php - 开始 oop php 问题 : do constructors take the place of getter?

c# - 为什么我们不能在派生类中使用带参数的构造函数

java - 逆波兰计算器未返回正确的值

java - Hadoop 为每个映射器使用一个实例

java - Checker Framework 可以与 Error Prone 一起使用吗?

java - 如何将警告更改为容易出错的错误?

java - 使用 ErrorProne 强制执行类型注释?