Generate a UUID in Java

Posted in :

example:

import java.util.UUID;

class MyUuidApp {
    public static void main(String[] args) {
        UUID uuid = UUID.randomUUID();
        String uuidAsString = uuid.toString();
        System.out.println("Your UUID is: " + uuidAsString);
    }
}

輸出的長像:

f8c3de3d-1fea-4d7c-a8b0-29f63c4c3454

如果不要 -, 可以這樣寫:

final String uuid = UUID.randomUUID().toString().replace("-", "");
System.out.println("uuid = " + uuid);

Java UUID Class Methods

MethodsDescription
clockSequence()It returns the clock sequence value associated with this specified UUID.
compareTo()The method compares the UUID with the specific UUID.
equals()The method compares this object to the specified object.
fromString()It generates a UUID from the String representation.
getLeastSignificantBits()It returns the least significant 64 bits of this UUID’s 128-bit value.
getMostSignificantBits()It returns the most significant 64 bits of this UUID’s 128-bit value.
hashCode()It returns a hash code for this UUID.
nameUUIDFromBytes()It retrieves a version-3 (name-based) UUID based on the specified byte array.
node()It returns a node value that is associated with the specified UUID.
randomUUID()It returns a randomly generated UUID.
timestamp()It returns a timestamp value associated with this specified UUID.
toString()It returns a String object representing this UUID.
variant()It is used to get the variant associated with the specified UUID.
version()We can get the version number associated with the specified UUID.

因為 UUID 是要在DB裡識別用的,也可以透過Database 裡的UUID 相關函數來取得。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *