@NotNull 对参数的 Getter 和 Setter 的影响

@NotNull implication on Getter and Setter of a Parameter

相信并使用 Which @NotNull Java annotation should I use?,我有一个 class,其中某些字段标记为 @NotNull [package javax.validation.constraints] 以传递给客户。 class 还为这些字段实现了默认的 getter 和 setter。下面的示例 class -

public class MyClass 
{
    public MyClass() {
    }

    @NotNull
    private String name;

    private Boolean bool;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Boolean isBool() {
        return bool;
    }

    public void setBool(Boolean bool) {
        this.bool = bool;
    }
}

我对 getter 在业务逻辑中的用法感到有些困惑 -

if(new MyClass().getName() !=null) {
    //do something
}

Is this null check not redundant, (if not) curious to know WHY?

另外,如果它是多余的,想考虑设置一个空值并获取参数的值。试一试 -

void test() {
    myClass.setName(null);
    if (myClass.getName() == null) {
        System.out.println("It should not be null"); // this got printed
    }
}

@NonNull 只是对您的工具的提示,它不会影响 java 语言本身处理空值的方式。它还要求对每个交互进行适当注释,以确保发现所有错误。

在您的情况下会发生这种情况,虽然 name 字段被注释,但与该字段交互的方法却没有注释,因此工具无法对这些方法及其可空性做出任何假设。

但是,如果您引入更多这样的注释:

public void setName(@Nullable String name) {
    this.name = name; // should now have a warning
}

@NonNull
public String getName() {
    return name;
}

现在工具应始终指示 new MyClass().getName() != null 为真。它还在 setName 中警告您将可空值设置为非空值 属性,这可能是错误的。

固定方式:

public void setName(@NonNull String name) {
    // setName(null) would cause a warning
    // Also add an exception if the annotation is ignored.
    this.name = Objects.requireNonNull(name);
}

/* or */

public void setName(@Nullable String name) {
    if (name == null) return; // Guard against setting null
    this.name = name;
}