Getter 和@Nonnull [英] Getter and @Nonnull

查看:23
本文介绍了Getter 和@Nonnull的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到了来自 eclipse 的警告,我知道我可以通过抑制警告来删除它,但我更想了解是什么使它可能为空.

I get a warning from eclipse and I know I can remove it with suppress warning but I'd prefer to understand what makes it thing it could be null.

package-info.java

package-info.java

@ParametersAreNonnullByDefault
package test;

import javax.annotation.ParametersAreNonnullByDefault;

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'
    }
}

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

I don't get why I get this warning...

附注:

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

public Test( @Nonnull final String s ) { -> The nullness annotation is redundant with a default that applies to this location

@Nonnull private final String s; -> 没有任何变化

推荐答案

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

The problem is that the @Nonnull annotation has no effects on fields. It is only supported for:

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

查看eclipse文档

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

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

So quite obviously - as Nonnull is not checked on fields - the compiler doesn't know that Test.s is Nonnull and complains about it.

The obvious solution would indeed be to add a @SuppressWarnings("null") on the field access (or on the method, if it's a simple getter):

public String getS() {
    @SuppressWarnings("null")
    @Nonnull String s = this.s;
    return s;
}

这篇关于Getter 和@Nonnull的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆