Groovy: Generate UUID Examples

by Didin J. on Mar 12, 2017 Groovy: Generate UUID Examples

A little examples of generating UUID using Groovy and run or executes Groovy codes online.

Sometimes the web or API developers need to generate random unique ID or UUID for their application. It uses for verification or another security purpose. Right now, we will show you a few examples of UUID generation using the build-in Java UUID. This time will be different than the previous tutorial because we will use online Groovy code runner. There are some Groovy and another language code runner or executor online, you can choose one of this code runner.

  1. Jdoodle
  2. Groovy Web Console
  3. Tutorials Point

Generate Groovy Random UUID

To start to generate Groovy random UUID just copy this code and paste in online Groovy code executor.

def verCode = UUID.randomUUID().toString()
println verCode

When you click 'run' or execute button, it will display UUID code in String format.


Find Out Version

To find out version and variant, run this codes.

UUID uuid = UUID.randomUUID()
println "Random UUID: "+uuid
println "UUID Variant: "+uuid.variant()
println "UUID Version: "+uuid.version()

That codes will display like this.

Random UUID: 536e97e9-0d29-43ec-b8d5-a505d3ee6a8f
UUID Variant: 2
UUID Version: 4

Create a UUID from the String

To create a UUID from the string standard representation, use these codes.

String uuidString = "536e97e9-0d29-43ec-b8d5-a505d3ee6a8f"
UUID uuid = UUID.fromString(uuidString)
println "UUID from String: "+uuid

The result will be the same as String UUID.

UUID from String: 536e97e9-0d29-43ec-b8d5-a505d3ee6a8f

That it's the examples of generating UUID using Groovy. You can apply that method in your Grails web application or other Groovy-based frameworks.

That just the basic. If you need more deep learning about Groovy and Grails you can take the following cheap course:

  • Mastering Grails. A Comprehensive Grails Course.
  • Groovy Scripting for Developers / Testers
  • Introduction to JVM Languages Clojure, Kotlin, and Groovy
  • Thanks.