📜  Java中的 TimeUnit valueOf() 方法及示例

📅  最后修改于: 2022-05-13 01:55:31.539000             🧑  作者: Mango

Java中的 TimeUnit valueOf() 方法及示例

TimeUnit 类valueOf()方法返回具有指定名称的该类型的枚举常量。该字符串必须与用于在此类型中声明枚举常量的标识符完全匹配。 (不允许使用无关的空白字符。)

句法:

public static TimeUnit valueOf(String name)

参数:此方法接受一个强制参数名称,它是要返回的枚举常量的名称。

返回值:此方法返回具有指定名称的枚举常量

异常:此方法抛出以下异常:

  • IllegalArgumentException – 如果此枚举类型没有具有指定名称的常量
  • NullPointerException – 如果参数为空

下面的程序说明了 TimeUnit valueOf() 方法的实现:

方案一:

// Java program to demonstrate
// valueOf() method of TimeUnit Class
  
import java.util.concurrent.*;
  
class GFG {
    public static void main(String args[])
    {
  
        // Create an object of TimeUnit class
        // using valueOf() method
        // Below statement is equivalent to
        // TimeUnit Days = TimeUnit.DAYS;
        TimeUnit Days = TimeUnit.valueOf("DAYS");
  
        // Print the Enum of TimeUnit Object
        System.out.println("TimeUnit object "
                           + "is of type: "
                           + Days);
  
        // Convert current object to Hours
        System.out.println("1 Day = "
                           + Days.toHours(1)
                           + " Hours");
    }
}
输出:
TimeUnit object is of type: DAYS
1 Day = 24 Hours

程序2:演示NullPointerException

// Java program to demonstrate
// valueOf() method of TimeUnit Class
  
import java.util.concurrent.*;
  
class GFG {
    public static void main(String args[])
    {
  
        try {
  
            System.out.println("Trying to create "
                               + "TimeUnit object "
                               + "using null Enum type");
  
            // Create an object of TimeUnit class
            // using valueOf() method
            // by passing null as parameter
            TimeUnit Days = TimeUnit.valueOf(null);
        }
  
        catch (NullPointerException e) {
            System.out.println("\nException thrown: " + e);
        }
    }
}
输出:
Trying to create TimeUnit object using null Enum type

Exception thrown: java.lang.NullPointerException: Name is null

程序 3:演示 IllegalArgumentException

// Java program to demonstrate
// valueOf() method of TimeUnit Class
  
import java.util.concurrent.*;
  
class GFG {
    public static void main(String args[])
    {
  
        try {
  
            System.out.println("Trying to create "
                               + "TimeUnit object "
                               + "using ABCD Enum type");
  
            // Create an object of TimeUnit class
            // using valueOf() method
            // by passing ABCD as parameter
            TimeUnit Days = TimeUnit.valueOf("ABCD");
        }
  
        catch (IllegalArgumentException e) {
            System.out.println("\nException thrown: " + e);
        }
    }
}
输出:
Trying to create TimeUnit object using ABCD Enum type

Exception thrown: java.lang.IllegalArgumentException: No enum constant java.util.concurrent.TimeUnit.ABCD