相关疑难解决方法(0)

如何更有效地使用@Nullable和@Nonnull注释?

我可以看到@Nullable@Nonnull注释可以在防止有用NullPointerException秒,但他们并不很远传播.

  • 在一个间接层之后,这些注释的有效性完全下降,所以如果你只添加一些注释,它们就不会传播得很远.
  • 由于这些注释没有得到很好的执行,因此存在假设标记的值@Nonnull不为空并因此不执行空检查的危险.

下面的代码会导致标有一个参数@Nonnullnull没有提出任何投诉.它会NullPointerException在运行时抛出.

public class Clazz {
    public static void main(String[] args){
        Clazz clazz = new Clazz();

        // this line raises a complaint with the IDE (IntelliJ 11)
        clazz.directPathToA(null);

        // this line does not
        clazz.indirectPathToA(null); 
    }

    public void indirectPathToA(Integer y){
        directPathToA(y);
    }

    public void directPathToA(@Nonnull Integer x){
        x.toString(); // do stuff to x        
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法使这些注释更严格地执行和/或进一步传播?

java annotations nullable nullpointerexception code-standards

120
推荐指数
7
解决办法
14万
查看次数