具有驼峰大小写值的分组字符串常量

Grouped string constants with camel case values

我们的目标是拥有一个带有驼峰大小写值的分组字符串常量。 理想情况下是:public enum Attribute {Measures, MeasuresLevel}。 但是它不符合命名约定:常量名称应该是大写的。 以下解决方案看起来像是数据重复:

public enum Attribute {
    MEASURES("Measures"), 
    MEASURES_LEVEL("MeasuresLevel");

    private final String value;

    Attribute(String value) {
        this.value = value;
    }
}

非常欢迎任何替代方案和建议。谢谢

将其放入您的枚举中

@Overwrite
public String toString(){
    String[] share = this.name().split("_");
    String camel = "";
    for(String s : share) {
        camel += s.charAt(0) + s.substring(1).toLowerCase();
    }
    return camel;
}

许多库都提供实用程序来转换为驼峰式大小写,例如 Guava :

Stream.of(Attribute.values())
    .map(attr -> attr.toString())
    .map( attr -> CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, attr))
    .forEach(System.out::println);

看看 Guava documentation