在java中使用枚举类型时
public enum TestEnum{
TEST1("test1"),
TEST2("test2"),
TEST3("test3"),
TEST4("test4"),;
private TestEnum(String code) {
this.code = code;
}
private String code;
public String getText() {
return this.getText();
}
public String getCode() {
return this.code;
}
}
当想要通过一个String获取枚举时,默认可以使用枚举本身提供的 ValueOf,但是是需要两个参数,
特殊的地方是,String类型的valueOf(String) 方法 ,枚举给隐士提供一个静态方法。
其他类型就需要自己定义喽。
TestEnum.valueOf("TEST1");形式获取
以下是API描述。
public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name)
Note that for a particular enum type T
, the implicitly declared public static T valueOf(String)
method on that enum may be used instead of this method to map from a name to the corresponding enum constant. All the constants of an enum type can be obtained by calling the implicit public static T[] values()
method of that type.
-
Type Parameters:
-
T
- The enum type whose constant is to be returned
Parameters:
-
enumType
- theClass
object of the enum type from which to return a constant -
name
- the name of the constant to return
Returns:
- the enum constant of the specified enum type with the specified name Throws:
-
IllegalArgumentException
- if the specified enum type has no constant with the specified name, or the specified class object does not represent an enum type -
NullPointerException
- ifenumType
orname
is null
Since:
- 1.5