避免重复文字声纳错误

Sof*_*ane 5 java sonarqube

我正在使用 SonarQube 来验证和检查我的 Java 代码,并且我遇到了避免枚举类类型中重复文字的问题,下面是一个示例:

public enum Products {

  A ("Product A"),
  C ("Product A"),
  D ("Product B"),
  P ("Product B");

  private String name = "";

  Products (String name){
    this.name = name;
  }

  public String toString(){
    return name;
  }
}
Run Code Online (Sandbox Code Playgroud)

Sonar 告诉我将字符串“Product A”和“Product B”声明为常量字段,但不能在 Enum 类型类中声明变量。

tea*_*ran 2

您可以在枚举之外声明常量:

private static final String TYPE_A_NAME = "Type A";

public enum Type {

    TYPEA(TYPE_A_NAME), TYPEB("B");

    private String value;

    Type(String value) {

    }
}
Run Code Online (Sandbox Code Playgroud)