如何根据价值获得枚举?
how to get enum on the basis of value?
我有一个枚举
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;
}
}
我想根据枚举的价值获取枚举。
我有 String
的值 Non-Residential
,那么我怎样才能得到返回`NonResidential.
的枚举
P.S 我想创造自己的魔法而不是 java 支持的东西。
我已经读出了很多问题,比如 this 但我想要不同的答案。
使用valueOf
.
Category.valueOf("Non-Residential");
这将 return 你的枚举。
这里没有魔法,因为它是您自己定义的字段 ('category'),您应该编写自己的静态方法来通过它进行搜索。例如:
public enum Category {
...
public static Category findByName(String cat){
// loop over Category.values() and find the requested cat
}
顺便说一句,如果您提供枚举名称(例如 "NonResidential"),ValueOf 将起作用,但它不适用于类别名称(例如,"non-residential")
我有一个枚举
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;
}
}
我想根据枚举的价值获取枚举。
我有 String
的值 Non-Residential
,那么我怎样才能得到返回`NonResidential.
P.S 我想创造自己的魔法而不是 java 支持的东西。 我已经读出了很多问题,比如 this 但我想要不同的答案。
使用valueOf
.
Category.valueOf("Non-Residential");
这将 return 你的枚举。
这里没有魔法,因为它是您自己定义的字段 ('category'),您应该编写自己的静态方法来通过它进行搜索。例如:
public enum Category {
...
public static Category findByName(String cat){
// loop over Category.values() and find the requested cat
}
顺便说一句,如果您提供枚举名称(例如 "NonResidential"),ValueOf 将起作用,但它不适用于类别名称(例如,"non-residential")