【问题标题】:Grouped string constants with camel case values具有驼峰式值的分组字符串常量
【发布时间】:2017-10-12 13:26:35
【问题描述】:

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

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

    private final String value;

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

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

【问题讨论】:

  • 你有什么问题?
  • 为什么不遵守约定?

标签: java enums camelcasing


【解决方案1】:

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

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

看看番石榴documentation

【讨论】:

    【解决方案2】:

    把它放到你的枚举中

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      • 2012-01-20
      • 2015-05-11
      • 1970-01-01
      • 2023-02-20
      • 2017-03-13
      相关资源
      最近更新 更多