📜  groovy random uuid - Groovy (1)

📅  最后修改于: 2023-12-03 14:41:39.171000             🧑  作者: Mango

Groovy Random UUID - Groovy

In Groovy, generating a random UUID is incredibly easy. UUID stands for Universally Unique Identifier, which is a 128-bit value used for identifying information. It is globally unique and can be used for data synchronization, verification, and several other things.

To generate a random UUID in Groovy, you can use the UUID class. The randomUUID() method of this class generates a random UUID that can be used for various purposes.

Here's an example of how to generate a random UUID in Groovy:

import java.util.UUID

def myUuid = UUID.randomUUID()

print myUuid.toString()

In the code above, we import the UUID class and then assign a random UUID generated by the randomUUID() method to the variable myUuid. You can then print this UUID by calling the toString() method of the UUID class.

The toString() method returns a formatted string representation of the UUID, which looks like this:

1be8d374-c9f9-4cde-9243-0918a43f0d1a

If you need to generate a UUID object that is based on a name or namespace, you can use the nameUUIDFromBytes() method of the UUID class. Here's an example:

import java.util.UUID

def name = "example.com"
def namespaceBytes = name.getBytes()

def myUuid = UUID.nameUUIDFromBytes(namespaceBytes)

print myUuid.toString()

In the code above, we create a UUID based on a name "example.com" by converting it to bytes and passing it to the nameUUIDFromBytes() method. The resulting UUID is then printed to the console.

Overall, generating a random UUID in Groovy is easy and can be done using the UUID class's randomUUID() method. If you need to generate a UUID based on a name or namespace, you can use the nameUUIDFromBytes() method instead.