TimeUnit类的valueOf()方法返回具有指定名称的此类型的枚举常量。该字符串必须与用于声明此类型的枚举常量的标识符完全匹配。 (不允许使用多余的空格字符。)
用法:
public static TimeUnit valueOf(String name)
参数:此方法接受必需的参数名称,该名称是要返回的枚举常量的名称。
返回值:此方法返回具有指定名称的枚举常量
异常:此方法引发以下异常:
- IllegalArgumentException–如果此枚举类型没有带有指定名称的常量
- NullPointerException –如果参数为null
以下示例程序旨在说明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
相关用法
- Java TimeUnit values()用法及代码示例
- Java TimeUnit toMicros()用法及代码示例
- Java TimeUnit toMillis()用法及代码示例
- Java TimeUnit toMinutes()用法及代码示例
- Java TimeUnit toSeconds()用法及代码示例
- Java TimeUnit toHours()用法及代码示例
- Java TimeUnit toNanos()用法及代码示例
- Java TimeUnit convert()用法及代码示例
- Java TimeUnit sleep()用法及代码示例
- Java TimeUnit toDays()用法及代码示例
- Java TextStyle valueOf()用法及代码示例
- Java ChronoUnit valueOf()用法及代码示例
- Java ChronoField valueOf()用法及代码示例
- Java DayOfWeek valueOf()用法及代码示例
注:本文由纯净天空筛选整理自RishabhPrabhu大神的英文原创作品 TimeUnit valueOf() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。