enum valueof
枚举类valueOf()方法 (Enum Class valueOf() method)
valueOf() method is available in java.lang package.
valueOf()方法在java.lang包中可用。
valueOf() method is used to retrieve the enum constants of the given parameter en_ty(enum type) with the given parameter en_name(enum name) and we need to remember one thing the enum name specified in the method must be the same as declared as enum constant in this enum type.
valueOf()方法用于检索具有给定参数en_name(枚举名称)的给定参数en_ty(枚举类型)的枚举常量,我们需要记住一件事,该方法中指定的枚举名称必须与声明为相同此枚举类型的枚举常量。
valueOf() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
valueOf()方法是一种非静态方法,只能通过类对象访问,如果尝试使用类名称访问该方法,则会收到错误消息。
valueOf() method may throw an exception at the time of retrieving enum constants:
在检索枚举常量时, valueOf()方法可能会引发异常:
- IllegalArgumentException: When the given enum type does not contain enum constants with the given name.IllegalArgumentException :当给定的枚举类型不包含具有给定名称的枚举常量时。
- NullPointerException: When the given first parameter represents null.NullPointerException :当给定的第一个参数表示null时。
Syntax:
句法:
public static T valueOf(Class<T> en_ty , String en_name);
Parameter(s):
参数:
Class<T> en_ty – represents the Class object of the enum type which return a constant.
Class <T> en_ty –表示枚举类型的Class对象,该对象返回一个常量。
String en_name – represents the name of enum constants.
字符串en_name –表示枚举常量的名称。
Return value:
返回值:
The return type of this method is T, it returns enum constant along with the given enum name.
此方法的返回类型为T ,它返回枚举常量以及给定的枚举名称。
Example:
例:
// Java program to demonstrate the example
// of T valueOf(Class<T> en_ty , String en_name)
// method of Enum
enum Month {
JAN,
FEB,
MAR,
APR,
MAY;
}
public class ValueOf {
public static void main(String args[]) {
Month m1 = Month.valueOf("JAN");
Month m2 = Month.valueOf("FEB");
Month m3 = Month.valueOf("MAR");
Month m4 = Month.valueOf("APR");
Month m5 = Month.valueOf("MAY");
System.out.println("Display value: ");
// By using valueOf() method is to return the value of
// enum constant
System.out.println("Month.valueOf(JAN) " + " " + m1.toString());
System.out.println("Month.valueOf(FEB) " + " " + m2.toString());
System.out.println("Month.valueOf(MAR)" + " " + m3.toString());
System.out.println("Month.valueOf(APR)" + " " + m4.toString());
System.out.println("Month.valueOf(MAY)" + " " + m5.toString());
}
}
Output
输出量
Display value:
Month.valueOf(JAN) JAN
Month.valueOf(FEB) FEB
Month.valueOf(MAR) MAR
Month.valueOf(APR) APR
Month.valueOf(MAY) MAY
翻译自: https://www.includehelp.com/java/enum-valueof-method-with-example.aspx
enum valueof