转:http://www.yiibai.com/java/lang/enum_valueof.html
java.lang.Enum.valueOf() 方法返回指定名称enumtype的枚举常量。该名称必须用于声明在此类型的枚举常量的标识符完全匹配。
声明
以下是java.lang.Enum.valueOf()方法的声明
public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name)
static <T extends Enum<T>> T valueOf(Class<T> enumType, String name)
参数
-
enumType -- 这是枚举类型,返回一个常量的类的对象。
-
name -- 这是常量,要返回的名称。
返回值
此方法返回具有指定名称的枚举类型的枚举常量。
异常
-
IllegalArgumentException -- 如果指定的枚举类型没有常量指定名称,或指定的类对象不表示枚举类型。
-
NullPointerException -- 如果 enumType 或 name 为 null.
例子
下面的例子显示java.lang.Enum.valueOf()方法的使用。
package com.yiibai;
import java.lang.*;
// enum showing Mobile prices
enum Mobile {
Samsung(400), Nokia(250),Motorola(325);
int price;
Mobile(int p) {
price = p;
}
int showPrice() {
return price;
}
}
public class EnumDemo {
public static void main(String args[]) {
System.out.println("CellPhone List:");
for(Mobile m : Mobile.values()) {
System.out.println(m + " costs " + m.showPrice() + " dollars");
}
Mobile ret;
ret = Mobile.valueOf("Samsung");
System.out.println("Selected : " + ret);
}
}
com.yiibai;
import java.lang.*;
// enum showing Mobile prices
enum Mobile {
Samsung(400), Nokia(250),Motorola(325);
int price;
Mobile(int p) {
price = p;
}
int showPrice() {
return price;
}
}
public class EnumDemo {
public static void main(String args[]) {
System.out.println("CellPhone List:");
for(Mobile m : Mobile.values()) {
System.out.println(m + " costs " + m.showPrice() + " dollars");
}
Mobile ret;
ret = Mobile.valueOf("Samsung");
System.out.println("Selected : " + ret);
}
}
让我们来编译和运行上面的程序,这将产生以下结果:
CellPhone List:
Samsung costs 400 dollars
Nokia costs 250 dollars
Motorola costs 325 dollars
Selected : Samsung
List:
Samsung costs 400 dollars
Nokia costs 250 dollars
Motorola costs 325 dollars
Selected : Samsung