Java TimeUnit valueOf()方法及示例

Java TimeUnit valueOf()方法及示例

TimeUnit类的valueOf()方法返回该类型的枚举常量,并指定名称。该字符串必须与用于声明该类型枚举常量的标识符完全匹配。(不允许有多余的空白字符)。

语法。

public static TimeUnit valueOf(String name)

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

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

异常。该方法会产生以下异常。

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

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

程序 1:

// 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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程