Getter和@Nonnull

xav*_*m02 7 java null annotations non-nullable

我从eclipse得到一个警告,我知道我可以通过抑制警告将其删除,但我更愿意理解是什么原因导致它可能为空.

package-info.java

@ParametersAreNonnullByDefault
package test;

import javax.annotation.ParametersAreNonnullByDefault;
Run Code Online (Sandbox Code Playgroud)

test.java

package test;


public class Test {
    public static void main( final String[ ] args ) {
        System.out.println( new Test( "a" ).getS( ) );
    }

    private final String s;

    public Test( final String s ) {
        this.s = s;
    }

    public String getS( ) {
        return this.s;//Null type safety: The expression of type String needs unchecked conversion to conform to '@Nonnull String'
    }
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么我得到这个警告......

PS:

public Test( @Nonnull final String s ) { - > nullness注释是多余的,默认值适用于此位置

@Nonnull private final String s; - >没什么变化

mme*_*mey 6

问题是@Nonnull注释对字段没有影响.它仅支持:

  • 方法参数
  • 方法返回值
  • 局部变量(在代码块内)

请参阅eclipse文档

很明显 - 因为Nonnull没有在字段上检查 - 编译器不知道Test.s是Nonnull并且抱怨它.

确实很明显的解决方案是在字段访问(或方法,如果它是一个简单的getter)上添加@SuppressWarnings("null"):

public String getS() {
    @SuppressWarnings("null")
    @Nonnull String s = this.s;
    return s;
}
Run Code Online (Sandbox Code Playgroud)