2

@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 中是非法的,因为不能像这样简单地制作一个块。这没什么大不了的,但我很好奇我是否错过了一个明显而优雅的解决方案。

4

1 回答 1

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;
        }
    }
}    

这样,只要您至少使用其中一个值,您就不会收到未使用的警告。

于 2012-09-28T19:12:43.290 回答