Kli*_*cou 2 java intellij-idea
有没有办法告诉IDEA以下内容可以:
public static void main(String[] args) {
String stringValue = args.length > 0 ? args[0] : null;
long longValue;
try {
longValue = Long.parseLong(stringValue);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("hmm...", e);
}
System.out.println(longValue);
}
Run Code Online (Sandbox Code Playgroud)
它坚持突出显示stringValue并警告“Argument stringValue might be null”。我知道可能会,但如果是的话,异常就会被捕获。
嗯,真的好吗?您本质上是使用异常来控制代码流。这通常被认为是一种反模式(为什么不使用异常作为常规控制流?)。
通过自己进行空检查可以轻松避免这种情况:
if (stringValue != null) {
longValue = Long.parseLong(stringValue);
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您想让代码保持原样并让null该方法处理案例parseLong(),您可以:
用注释你的方法@SuppressWarnings("ConstantConditions")
@SuppressWarnings("ConstantConditions")
public static void main(String[] args) {
String stringValue = args.length > 0 ? args[0] : null;
long longValue;
try {
longValue = Long.parseLong(stringValue);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("hmm...", e);
}
}
Run Code Online (Sandbox Code Playgroud)
添加评论//noinspection ConstantConditions
public static void main(String[] args) {
String stringValue = args.length > 0 ? args[0] : null;
long longValue;
try {
//noinspection ConstantConditions
longValue = Long.parseLong(stringValue);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("hmm...", e);
}
}
Run Code Online (Sandbox Code Playgroud)
altIntelliJ 通过按+来帮助我解决这两个问题enter,调出意图菜单,您可以在其中选择Supress for method或Supress for statements。
然而,我认为这两个都是特定于 IDE 的,所以我的建议就是不要发出警告。或者更好的是,您自己进行 null 检查。