如何将值转换为枚举? [英] How can I convert from a value to an enum?
本文介绍了如何将值转换为枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的枚举:
public enum Numbers {
ONE(1), TWO(2), THREE(3);
public final int num;
public Numbers(int num) {
this.num = num;
}
}
我想要能够从参数转换为枚举,例如从int 1
到枚举 ONE
。在Java Enums中有内置的机制吗?或者我必须为自己编写自己的逻辑?
I want to be able to convert from argument to enum, for instance from the int 1
to the enum ONE
. Is there any built-in mechanism in Java Enums to do this, or do I have to write my own logic for it?
推荐答案
是的,您必须编写自己的逻辑,因为 num
变量是您自己逻辑的一部分:
Yes you have to write your own logic as the num
variable is a part of your own logic :
public enum Numbers {
ONE(1), TWO(2), THREE(3);
public final int num;
private Numbers(int num) {
this.num = num;
}
public static Numbers getNumber(int i){
for(Numbers number : Numbers.values()){
if(i == number.num){
return number;
}
}
throw new IllegalArgumentException("This number doesn't exist");
}
}
这篇关于如何将值转换为枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文