【发布时间】:2015-07-17 09:51:54
【问题描述】:
使用 IntelliJ 注释,可以在方法参数为 null 的情况下以两种不同的方式声明函数失败(并将它们组合在一起,总共三个):
我可以在方法参数上使用@NotNull 注释来声明该参数永远不应该为空。
@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());
}
这三种情况哪一种最好用?
【问题讨论】:
-
这是@javax.validation.NotNull 吗?
-
这是@org.jetbrains.annotations.NotNull
标签: java intellij-idea annotations intellij-14