Create a GUID in Java
What are some of the best ways to create a GUID in Java?
java.util.UUID.randomUUID();
Have a look at the UUID class bundled with Java 5 and later.
For example:
- If you want a random UUID you can use the randomUUID method.
- If you want a UUID initialized to a specific value you can use the UUID constructor or the fromString method.
Just to extend Mark Byers's answer with an example:
import java.util.UUID;
public class RandomStringUUID {
public static void main(String[] args) {
UUID uuid = UUID.randomUUID();
System.out.println("UUID=" + uuid.toString() );
}
}
It depends what kind of UUID you want.
-
The standard Java
UUID
class generates Version 4 (random) UUIDs. (UPDATE - Version 3 (name) UUIDs can also be generated.) It can also handle other variants, though it cannot generate them. (In this case, "handle" means constructUUID
instances fromlong
,byte[]
orString
representations, and provide some appropriate accessors.) -
The Java UUID Generator (JUG) implementation purports to support "all 3 'official' types of UUID as defined by RFC-4122" ... though the RFC actually defines 4 types and mentions a 5th type.
For more information on UUID types and variants, there is a good summary in Wikipedia, and the gory details are in RFC 4122 and the other specifications.
The other Answers are correct, especially this one by Stephen C.
Reaching Outside Java
Generating a UUID value within Java is limited to Version 4 (random) because of security concerns.
If you want other versions of UUIDs, one avenue is to have your Java app reach outside the JVM to generate UUIDs by calling on:
-
Command-line utility
Bundled with nearly every operating system.
For example,uuidgen
found in Mac OS X, BSD, and Linux. -
Database server
Use JDBC to retrieve a UUID generated on the database server.
For example, theuuid-ossp
extension often bundled with Postgres. That extension can generates Versions 1, 3, and 4 values and additionally a couple variations: -
uuid_generate_v1mc()
– generates a version 1 UUID but uses a random multicast MAC address instead of the real MAC address of the computer. -
uuid_generate_v5(namespace uuid, name text)
– generates a version 5 UUID, which works like a version 3 UUID except that SHA-1 is used as a hashing method. -
Web Service
For example, UUID Generator creates Versions 1 & 3 as well as nil values and GUID.