繁体   English   中英

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

[英]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)

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

容易出错的定义了ConstructorLeaks这个问题:

在构造函数执行期间,使新实例可供其他代码访问很危险。 实例的字段(包括最终字段)可能尚未初始化,并且执行实例方法可能会产生意外的结果。

...而且从您的代码来看,您没有违反规则,Java文档也写过关于将其与构造函数一起使用的说法,这是一个错误的肯定, 这里也报道了同样的问题。

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

我很确定这是一个错误。

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

但是,构造函数链接非常好,并且通常是一个好习惯。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM