Getter和@Nonnull [英] Getter and @Nonnull
问题描述
我从Eclipse的一个警告,我知道我可以用燮preSS警告删除,但我想preFER明白是什么使得它的东西它可能为空。
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
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...
PS:
公开测试(@Nonnull最后一个String){
- >的NULL的含量注释是多余的适用于该位置的默认
public Test( @Nonnull final String s ) {
-> The nullness annotation is redundant with a default that applies to this location
@Nonnull私人最终的String;
- >没有什么变化
@Nonnull private final String s;
-> nothing changes
推荐答案
的问题是,@Nonnull标注有场无影响。它仅支持:
The problem is that the @Nonnull annotation has no effects on fields. It is only supported for:
- 方法参数
- 方法的返回值
- 局部变量(一个code座内)
<一个href=\"http://help.eclipse.org/juno/index.jsp?topic=/org.eclipse.jdt.doc.user/tasks/task-using_null_annotations.htm\">See Eclipse文档
所以很明显 - 作为非空不上的字段检查 - 编译器不知道Test.s为非空和抱怨它。
明显的解决方案确实是在球场上获得加@燮pressWarnings(空)(或方法,如果它是一个简单的getter):
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屋!