我们有一些类具有共享构造函数逻辑的常用模式:
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/