何时使用@Contract("null -> fail") 何时使用@NotNull
When to use @Contract("null -> fail") and when to use @NotNull
借助 IntelliJ 注释,可以在方法参数为 null 的情况下以两种不同的方式声明函数失败(并将它们组合起来,总共三种方式):
我可以在方法参数上使用 @NotNull
注释来声明该参数永远不应该为 null。
@NotNull
public static String doSomething(@NotNull CharSequence parameter) throws NullPointerException {
return String.format("This is the value: %s, of type %s",
Objects.requireNonNull(parameter),
parameter.getClass().getName());
}
或者,我可以使用 @Contract("null -> fail")
注释,它声明如果第一个参数为 null,该方法将抛出异常。
@NotNull
@Contract("null -> fail")
public static String doSomething(CharSequence parameter) throws NullPointerException {
return String.format("This is the value: %s, of type %s",
Objects.requireNonNull(parameter),
parameter.getClass().getName());
}
最后,我什至可以同时使用两者,而且我的 IntelliJ IDEA 14.1.4 没有任何抱怨:
@NotNull
@Contract("null -> fail")
public static String doSomething(@NotNull CharSequence parameter) throws NullPointerException {
return String.format("This is the value: %s, of type %s",
Objects.requireNonNull(parameter),
parameter.getClass().getName());
}
这三种情况,哪种最好用?
在你的情况下,我会使用@NotNull,因为:
- 这是一个更具体的注释,IDEA 能够基于它生成更具体的警告
- IDEA 可以生成运行时断言,确保它真的不为空
@Contract 注解是一个更强大但更不具体的工具。它允许您表达更复杂的合同,缺点是生成的编辑器警告可能更模糊,并且不会自动添加运行时检查。
借助 IntelliJ 注释,可以在方法参数为 null 的情况下以两种不同的方式声明函数失败(并将它们组合起来,总共三种方式):
我可以在方法参数上使用 @NotNull
注释来声明该参数永远不应该为 null。
@NotNull
public static String doSomething(@NotNull CharSequence parameter) throws NullPointerException {
return String.format("This is the value: %s, of type %s",
Objects.requireNonNull(parameter),
parameter.getClass().getName());
}
或者,我可以使用 @Contract("null -> fail")
注释,它声明如果第一个参数为 null,该方法将抛出异常。
@NotNull
@Contract("null -> fail")
public static String doSomething(CharSequence parameter) throws NullPointerException {
return String.format("This is the value: %s, of type %s",
Objects.requireNonNull(parameter),
parameter.getClass().getName());
}
最后,我什至可以同时使用两者,而且我的 IntelliJ IDEA 14.1.4 没有任何抱怨:
@NotNull
@Contract("null -> fail")
public static String doSomething(@NotNull CharSequence parameter) throws NullPointerException {
return String.format("This is the value: %s, of type %s",
Objects.requireNonNull(parameter),
parameter.getClass().getName());
}
这三种情况,哪种最好用?
在你的情况下,我会使用@NotNull,因为:
- 这是一个更具体的注释,IDEA 能够基于它生成更具体的警告
- IDEA 可以生成运行时断言,确保它真的不为空
@Contract 注解是一个更强大但更不具体的工具。它允许您表达更复杂的合同,缺点是生成的编辑器警告可能更模糊,并且不会自动添加运行时检查。