2017-10-12 76 views
-1

目標是將大小寫字符串常量與駝峯大小寫值組合在一起。 理想情況是:public enum Attribute {Measures, MeasuresLevel}。 但是它不符合命名約定:常量名稱應該是大寫的。 下面的解決方案看起來像一個重複數據:分組字符串常量與駝峯大小寫值

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

    private final String value; 

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

任何替代方案,建議都非常歡迎。謝謝。

+2

看看你是什麼題? –

+0

爲什麼不遵循約定? – Valentun

回答

0

將這個到您的枚舉

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

相關問題