Generating a UUID in Java
Published on October 13, 2015 by Bo Andersen
Generating a UUID in Java is extremely easy. In fact, it can be done with a single line of code! To generate a type 4 UUID in Java, simply run the following line of code.
String uuid = UUID.randomUUID().toString(); // Example: e03913fb-5951-4964-a88b-47371641fd17
Because you will likely generate UUIDs in many different contexts, here is a handy helper utility for you.
public final class GeneralUtils { private GeneralUtils() { } public static String generateUUID() { return UUID.randomUUID().toString(); } }
It can then be used as follows.
String uuid = GeneralUtils.generateUUID();
Not a huge difference, but I personally find the last line easier to remember. Plus, as long as I remember where my UUID method resides, intelli sense will guide me the rest of the way.
I hope this helps.
2 comments on »Generating a UUID in Java«
where I can find the GeneralUtils class ?
This details out the version 4 UUIDs
Hello,
You can simply copy the code from this post and add the class to your particular project.