我有一个枚举
public enum Category {
NonResidential("Non-Residential"), Residential("Residential");
private String category;
BuildingAssetCategory(String s) {
category = s;
}
public String getType() {
return category;
}
public void setType(String type) {
this.category = type;
}
}
我想根据枚举所具有的值(value)来获取枚举。
我有String
值(value)Non-Residential
,那么我怎样才能让枚举返回`NonResidential。
P.S 我想创造自己的魔法而不是java支持的东西。 我读过很多问题,例如 this但我想要不同的答案。
最佳答案
这里没有魔法,因为它是您自己的定义字段(“类别”),您应该编写自己的静态方法来通过它进行搜索。例如:
public enum Category {
...
public static Category findByName(String cat){
// loop over Category.values() and find the requested cat
}
顺便说一句,如果您提供枚举名称(例如“NonResidential”),则 ValueOf 将起作用,但它不适用于类别名称(例如“non-residential”)
关于java - 如何根据值获取枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29293097/