有没有办法标记(例如注释)Java方法从未返回? [英] Is there a way to mark (e.g. annotate) a Java method as never returning?

查看:175
本文介绍了有没有办法标记(例如注释)Java方法从未返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用新的Eclipse 4.2(Juno)Null Analysis。

I just started using the new Eclipse 4.2 (Juno) Null Analysis.

这样的代码:

x = foo();
if (x == null)
    fail("x is null");
return x.bar();

我收到警告,x可能为空。但它不可能,因为失败总是抛出,因此永远不会返回。 (有更好的程序间分析,可能会自动确定这一点,但目前看来似乎没有。)

I'm getting warnings that x may be null. But it can't be, because fail always throws and therefore never returns. (With better inter-procedural analysis it could presumably determine this automatically, but it currently doesn't seem to.)

显然,有一些方法来重写代码以获取围绕警告,但是我想要的是一种方法来指示(例如注释),它不会返回。

Obviously, there are ways to rewrite the code to get around the warning, but what I'd like is a way to indicate (e.g. an annotation) that fail never returns.

我还试图用@SuppressWarnings来抑制警告(null),但是没有起作用。

I also tried to suppress the warning with @SuppressWarnings("null") but that didn't work.

摆脱警告的一种方法是添加: assert x!= null ; (假设你已经打开设置,以在null分析中包含断言)

One way to get rid of the warning is to add: assert x != null; (assuming you have turned on the setting to include asserts in null analysis)

在GCC C ++中我可以做: void fn __attribute__((noreturn))

In GCC C++ I can do: void fn __attribute__ ((noreturn))

推荐答案

如下:

public RuntimeException fail(String message) {
  throw new RuntimeException(message);
}

所以你可以写 throw fail(x空)。当然, fail 将总是最终执行抛出,而不是 throw ,但是足以让编译器放心该行将永远抛出。

so you can write throw fail("x is null"). Of course, fail will always end up doing the throwing, not the throw, but it's enough to reassure the compiler that that line will always throw.

这篇关于有没有办法标记(例如注释)Java方法从未返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆