我有内部枚举的课程:
public class Apartment implements Comparable<Apartment> {
// more properties
private StarRating rating;
private SleepPlaces sleepPlaces;
public enum StarRating {
TWO_STARS("two stars"), THREE_STARS("three stars"), FOUR_STARS("four stars"), FIVE_STARS("five stars");
private String description;
private StarRating(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
public void setRating(StarRating rating) {
this.rating = rating;
}
正如您所看到的,它具有description
值,用于描述此枚举元素。
我需要从jsp
选择字段设置枚举。跳过一些jsp代码,我们有一些字符串值,如 - two stars
,由用户选择。
我想将它设置为Apartment
对象,但我无法使用枚举valueOf()
来执行此操作。它抛出IllegalArgumentException
。
一些示例:
public class Test {
public static void main(String[] args) {
Apartment app = new Apartment();
String rating2 = "TWO_STARS";
app.setRating(Enum.valueOf(Apartment.StarRating.class, rating2));
System.out.println("here is rating: " + app.getRating());
String rating = "two stars";
app.setRating(Enum.valueOf(Apartment.StarRating.class, rating));
System.out.println("here is rating: " + app.getRating());
}
}
输出:
here is rating: TWO_STARS
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant com.lelyak.model.Apartment.StarRating.two stars
at java.lang.Enum.valueOf(Enum.java:236)
at com.lelyak.application.Test.main(Test.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
如何为rating
值实现第二个变体?有什么建议吗?
如何根据枚举值设置枚举元素?
解决方案:
为枚举添加静态方法:
public static StarRating getByDescription(String description){
if(description != null){
for(StarRating sr : StarRating.values()){
if(description.equalsIgnoreCase(sr.description)){
return sr;
}
}
}
return null;
}
答案 0 :(得分:1)
我认为你实际问的是如何通过description
设置枚举。没有内置的构造可以让你这样做,但是你可以在枚举中添加一个静态方法:
public static StarRating getByDescription(String description){
if(description == null){
return null;
}
for(StarRating sr : StarRating.values()){
if(description.equals(sr.description)){
return sr;
}
}
return null;
}
答案 1 :(得分:0)
您无法使用方法'Enum.valueOf'按说明解析枚举。您可以在“公寓”类中编写自己的方法来解决它