java 使用nullable,使用@Nullable和@Nonnull Java注解更多的用途不同?

I can see that @Nullable and @Nonnull annotations could be helpful in preventing NullPointerExceptions but they do not propagate very far.

The effectiveness of these annotations drop off completely after one level of indirection, so if you only add a few they don't propagate very far.

Since these annotations are not well enforced there is a danger of assuming a value marked with @Nonnull is not null and consequently not performing null checks.

The code below causes a parameter marked with @Nonnull to be null without raising any complaints. It throws a NullPointerException when it is run.

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

}

}

Is there a way to make these annotations more strictly enforced and/or propagate further?

解决方案

Short answer: I guess these annotations are only useful for your IDE to warn you of potentially null pointer errors.

As said in the "Clean Code" book, you should check your public method's parameters and also avoid checking invariants.

Another good tip is never returning null values, but using Null Object Pattern instead.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值