示例:
void finishApplication() {
System.exit(0);
System.out.println("Application is terminated"); // 不可到达的代码
}
请注意,此检查依赖于方法约定推断。 特别是,如果您调用始终引发异常的 static 或 final 方法,将推断“始终失败”约定,并且方法调用之后的代码将被视为不可到达。 例如:
void run() {
performAction();
System.out.println("Action is performed"); // 不可到达的代码
}
static void performAction() {
throw new AssertionError();
}
如果使用任何类型的代码后处理,这可能会导致误报,例如,如果注解处理器稍后将方法体替换为有用的内容。 为了避免误报警告,请使用 org.jetbrains:annotations
软件包中的显式 @org.jetbrains.annotations.Contract
注解来禁止自动约定推断:
void run() {
performAction();
System.out.println("Action is performed"); // 不再有警告
}
@Contract("-> _") // 实现将被替换
static void performAction() {
throw new AssertionError();
}
2024.1 最新变化