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.

- Jdoodle
- Groovy Web Console
- Tutorials Point

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.

5bd9bca8-b355-4a64-9157-11b165df034f

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

To creates a UUID from the string standard representation, use this 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.

Thanks.

Loading…