Generate UUID in Groovy

Table of Contents

Method 1: Using java.util.UUID

The easiest way to generate a UUID in Groovy is by using the java.util.UUID.randomUUID() method. This method generates a random UUID using a cryptographically strong pseudo-random number generator.

import java.util.UUID

def uuid = UUID.randomUUID().toString()

println "Generated UUID: $uuid"

This code snippet generates a random UUID using the randomUUID() method and converts it to a string.

Method 2: Using Time-Based UUID

If you need to generate a UUID based on the current timestamp, you can use the java.util.UUID.nameUUIDFromBytes() method along with a byte array containing the timestamp.

import java.util.UUID

// Get current timestamp in milliseconds
def timestamp = System.currentTimeMillis()

// Convert timestamp to byte array
byte[] timestampBytes = ByteBuffer.allocate(8).putLong(timestamp).array()

// Generate time-based UUID
def uuid = UUID.nameUUIDFromBytes(timestampBytes).toString()

println "Generated time-based UUID: $uuid"

This code snippet generates a time-based UUID by first converting the current timestamp to a byte array and then using the nameUUIDFromBytes() method to generate the UUID.

References

  1. java.util.UUID documentation

Summary

In this tutorial, we explored two different ways of generating UUIDs in Groovy. The first method uses the java.util.UUID.randomUUID() method, which generates a random UUID. The second method generates a time-based UUID by converting the current timestamp to a byte array and using the java.util.UUID.nameUUIDFromBytes() method. Both methods provide a unique identifier that can be used in various applications.