java 关于枚举类型 valueOf方法

  在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)
Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)

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 - the  Class 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 - if  enumType or  name is null
Since:
1.5
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值