【问题标题】:@NotNull implication on Getter and Setter of a Parameter@NotNull 对参数的 Getter 和 Setter 的影响
【发布时间】:2017-02-24 01:54:07
【问题描述】:

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

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
}

null 检查不是多余的,(如果不是)很想知道WHY

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

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

【问题讨论】:

    标签: java getter-setter notnull


    【解决方案1】:

    @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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多