📜  Java中的 UUID fromString() 方法及示例

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

Java中的 UUID fromString() 方法及示例

Java中UUID 类fromString()方法用于从相同的标准字符串表示创建 UUID。

句法:

public static UUID fromString(String UUID_name)

参数:该方法采用一个参数UUID_name ,它是 UUID 的字符串表示形式。

返回值:该方法返回从指定字符串创建的实际UUID

异常:如果传递了无效的UUID_name ,该方法将引发IllegalArgumentException

下面的程序说明了 fromString() 方法的工作:

方案一:

// Java code to illustrate fromString() method
  
import java.util.*;
  
public class UUID_Demo {
    public static void main(String[] args)
    {
  
        // Get the string
        String UUID_name
            = "5fc03087-d265-11e7-b8c6-83e29cd24f4c";
  
        // Displaying the UUID
        System.out.println("The specified String is: "
                           + UUID_name);
  
        // Creating the UUID
        UUID UUID_1
            = UUID
                  .fromString(UUID_name);
  
        // Displaying the UUID
        System.out.println("The UUID from"
                           + " specified String: "
                           + UUID_1);
    }
}
输出:
The specified String is: 5fc03087-d265-11e7-b8c6-83e29cd24f4c
The UUID from specified String: 5fc03087-d265-11e7-b8c6-83e29cd24f4c

方案二:

// Java code to illustrate fromString() method
  
import java.util.*;
  
public class UUID_Demo {
    public static void main(String[] args)
    {
  
        // Get the string
        String UUID_name
            = "58e0a7d7-eebc-11d8-9669-0800200c9a66";
  
        // Displaying the UUID
        System.out.println("The specified String is: "
                           + UUID_name);
  
        // Creating the UUID
        UUID UUID_1
            = UUID
                  .fromString(UUID_name);
  
        // Displaying the UUID
        System.out.println("The UUID from"
                           + " specified String: "
                           + UUID_1);
    }
}
输出:
The specified String is: 58e0a7d7-eebc-11d8-9669-0800200c9a66
The UUID from specified String: 58e0a7d7-eebc-11d8-9669-0800200c9a66