我有一个与@SuppressWarnings("unused")
注释相关的基本问题。基本上,我想在我的类的声明部分中抑制代码块上未使用的警告。我不想在整个班级上禁止使用未使用的警告。
目前,我这样做:
public class MyClass {
//Constants
private final String ACCEPT = "Yes";
@SuppressWarnings("unused")
private final String DENY = "No"; //Not currently used
private final String TENTATIVE = "Maybe";
@SuppressWarnings("unused")
private final String POSTPONE = "Later"; //Not currently used
//Variables
private int counter;
....
我发现上面的代码有点乱,随机抛出的注释就像那样。我想做的是:
//Constants
@SuppressWarnings("unused")
{
private final String ACCEPT = "Yes";
private final String DENY = "No"; //Not currently used
private final String TENTATIVE = "Maybe";
private final String POSTPONE = "Later"; //Not currently used
}
//Variables
private int counter;
....
当然,这在Java中是非法的,因为块不能简单地这样做。这不是什么大不了的事,但我很好奇,如果我错过了一个明显而优雅的解决方案。
答案 0 :(得分:6)
如果你想要保留所有那些未使用的常量,那么就会有一个快速而肮脏的技巧;
public class MyClass {
//Variables
private int counter;
@SuppressWarnings("unused")
private static final class UnusedConstants{
private final String ACCEPT = "Yes";
private final String DENY = "No";
private final String TENTATIVE = "Maybe";
private final String POSTPONE = "Later";
}
}
我也会让它们变得静止,但是你的电话。
修改强>: 或者,我认为更好的是:
public class MyClass {
private enum Answer {
ACCEPT ("Yes"),
DENY ("No"),
TENTATIVE("Maybe"),
POSTPONE("Later");
private final String answer;
private Answer(String answer) {
this.answer = answer;
}
public String toString() {
return answer;
}
}
}
这样,只要您使用至少一个值,就不会获得未使用的警告。