- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何在 NetBeans 14 IDE 中禁用“不必要的 null 测试”警告?
NetBeans 作为一个众所周知的错误 1 2 3 4 它会错误地告诉您不需要对 null
进行测试。例如在下面的代码中:
import javax.validation.constraints.NotNull;
private void doSomething(@NotNull Object o) {
if (o == null) return;
//...do more stuff...
}
IDE 思考
o
参数被标记为 @NotNullo
o
必须不可能 null
if
语句是不必要的@NotNull 注解只是一个 IDE 提示,不是运行时保证。
null
您可以通过将 null
传递给 doSomething
方法来向自己证明这一点。 (我们甚至可以编写测试代码,这样 IDE 就不会生成任何提示或警告!):
Object o = getTestValue();
doSomething(o);
private Object getTestValue()
{
Object o = null;
return o;
}
private void doSomething(@NotNull Object o) {
Objects.requireNonNull(value);
//...do more stuff...
}
然后观察 doSomething
方法失败 - 因为 o
是 null
- 即使它被标记为 @NotNull。
现在,可能还有 @NotNull
的其他实现,或者其他添加运行时检查的编译器。我不是在说那些。 NetBeans IDE 14 警告是错误的,所以我需要禁用它。
但它只提供配置null deference 警告 - 我绝对想保留。
但没有任何有值(value)的东西出现:
但它肯定与 *unnecessary test for null没有有关。
但它不在那里。
但它不在那里。
但它不在那里。
这让我想到了我的问题:
最佳答案
您可以使用 Java 注释 @SuppressWarnings("null")
关闭“Unnecessary test for null”警告。该注释位于 java.lang 中,无需导入。
The OpenJDK Javadoc for SuppressWarnings for JDK 17 states :
Indicates that the named compiler warnings should be suppressed in theannotated element (and in all program elements contained in theannotated element) ... As a matter of style, programmers should alwaysuse this annotation on the most deeply nested element where it iseffective. If you want to suppress a warning in a particular method,you should annotate that method rather than its class.
来自 the linked documentation to section 9.6.4.5 of the Java Language Specification , @SuppressWarnings
似乎完全按照您的意愿行事,我强调了这一点:
9.6.4.5. @SuppressWarnings
Java compilers are increasingly capable of issuing helpful "lint-like"warnings. To encourage the use of such warnings, there should be someway to disable a warning in a part of the program when the programmerknows that the warning is inappropriate.
这是基于 OP 中的示例代码:
package suppression;
import javax.validation.constraints.NotNull; // Jakarta EE 8
//import jakarta.validation.constraints.NotNull; // Jakarta EE 9
public class Suppression {
public static void main(String[] args) {
Suppression supp = new Suppression();
Object o = supp.getTestValue();
supp.doSomething(o);
supp.doSomething2(o);
}
Object getTestValue() {
Object o = null;
return o;
}
private void doSomething(@NotNull Object o) {
if (o == null) {
System.out.println("Object is null!");
}
}
@SuppressWarnings("null")
private void doSomething2(@NotNull Object o) {
if (o == null) {
System.out.println("Object is null!");
}
}
}
这是 NetBeans 14 中该代码的屏幕截图,其中显示:
doSomething()
的第 22 行。@SuppressWarnings("null")
防止在第 30 行以其他相同的方法显示不需要的警告“Unnecessary test for null”doSomething2()
.关于java - 如何在 NetBeans 14 中禁用 "unnecessary test for null"警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72972146/
我是一名优秀的程序员,十分优秀!