Ant*_*val 5 java enums correctness
在我们的项目中,我们都有这种枚举.它们工作得很好,但我们不确定它们.
特别是使用getDocumentType(String)方法.
有没有办法避免迭代所有的Enums字段?
public enum DocumentType {
UNKNOWN("Unknown"),
ANY("Any"),
ASSET(Asset.class.getSimpleName()),
MEDIA(Media.class.getSimpleName()),
MEDIA35MM(Media.class.getSimpleName() + " 35mm");
private String label;
private DocumentType(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
public static DocumentType getDocumentType(String label){
for(DocumentType documentType : DocumentType.values()){
if(documentType.getLabel().equals(label)){
return documentType;
}
}
return UNKNOWN;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:检查newacct响应.她也没事.
由于写入枚举的限制,你将不得不在某处进行迭代.在理想的世界中,您将从DocumentType的构造函数中填充静态Map,但这是不允许的.
我能建议的最好的方法是在静态初始化程序中执行一次迭代,并将枚举存储在查找表中:
public enum DocumentType {
.... existing enum stuff here
private static final Map<String, DocumentType> typesByLabel = new HashMap<String, DocumentType>();
static {
for(DocumentType documentType : DocumentType.values()){
typesByLabel.put(documentType.label, documentType);
}
}
public static DocumentType getDocumentType(String label){
if (typesByLabel.containsKey(label)) {
return typesByLabel.get(label);
} else {
return UNKNOWN;
}
}
}
Run Code Online (Sandbox Code Playgroud)
至少你不会每次都进行迭代,虽然我怀疑你会看到任何有意义的性能提升.
| 归档时间: |
|
| 查看次数: |
460 次 |
| 最近记录: |