在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- theClassobject 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- ifenumTypeornameis null
Since:
- 1.5
本文详细介绍了Java中枚举类型的使用方法,包括如何定义枚举、枚举构造函数的使用及如何通过字符串获取枚举值。此外,还提供了枚举类型中valueOf方法的API描述。
817

被折叠的 条评论
为什么被折叠?



