[英]How to suppress Java compiler warnings for specific functions
We are always taught to make sure we use a break in switch statements to avoid fall-through. 我们总是被教导确保我们在switch语句中使用break来避免掉头。
The Java compiler warns about these situations to help us not make trivial (but drastic) errors. Java编译器警告这些情况,以帮助我们不要做出微不足道的(但是很严重的)错误。
I have, however, used case fall-through as a feature (we don't have to get into it here, but it provides a very elegant solution). 但是,我使用了case-fall-through作为一个功能(我们不必在这里进入它,但它提供了一个非常优雅的解决方案)。
However the compiler spits out massive amounts of warnings that may obscure warnings that I need to know about. 然而,编译器会发出大量警告,这些警告可能会掩盖我需要了解的警告。 I know how I can change the compiler to ignore ALL fall-through warnings, but I would like to implement this on a method-by-method basis to avoid missing a place where I did not intend for fall-through to happen.
我知道如何更改编译器以忽略所有直通警告,但我想在逐个方法的基础上实现这一点,以避免错过我不打算发生跌倒的地方。
Any Ideas? 有任何想法吗?
If you really, really must do this, and you are sure you are not making a mistake, check out the @SuppressWarnings annotation . 如果你真的,真的必须这样做,并且你确定你没有犯错,请查看@SuppressWarnings注释 。 I suppose in your case you need
我想在你的情况下你需要
@SuppressWarnings("fallthrough")
To complete other answer about SuppressWarnings
: 要完成有关
SuppressWarnings
其他答案:
@SuppressWarnings("fallthrough")
Try to supress all the fall-through warning at the compiler level is a bad thing: as you've explained, the cases where you need to pass through the warning are clearly identified. 尝试在编译器级别压制所有直通警告是一件坏事:正如您所解释的那样,您需要通过警告的情况会被清楚地识别出来。 Thus, it should be explicitly written in the code (the
@SuppressWarnings("fallthrough")
annotation with an optionnal comment is welcome). 因此,它应该明确地写在代码中(
@SuppressWarnings("fallthrough")
注释,欢迎使用optionnal注释)。 Doing so, you'll still have the fall-through warning if you really forget a break somewhere elese in your code. 这样做,如果您真的忘记了代码中某处的中断,您仍然会收到通知警告。
You could create a structure of 'if' statements in place of the switch. 您可以创建一个'if'语句结构来代替switch。 Might not be as visually pleasing however neither is warning supression.
可能不会在视觉上令人愉悦,但也不是警告抑制。
@SuppressWarnings("fallthrough")
Java has always followed the C-style of switch statements, where you need to explicititly break out of a switch unless you wish to simply fall through and execute the code in the case below. Java一直遵循C风格的switch语句,除非你希望简单地完成并执行下面的代码,否则你需要明确地断开交换机。 This can be dangerous of course and errors of this kind can be very hard to track down.
这当然是危险的,这种错误很难追查。 In the following example, case 1 lacks a break:
在以下示例中,案例1缺少中断:
@SuppressWarnings("fallthrough")
public void fallthroughTest(int i)
{
switch (i)
{
case 1:
// Execute both 1 and 2
case 2:
// Execute only 1
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.