Generate a GUID/UUID from Java?

Can anyone show me how to generate a GUID or UUID from Java code.  I am using JDK 1.2b4 and JSDK 2.0.

Who is Participating?
thresholdConnect With a Mentor Commented:
Do you want your JAVA GUID created as MS GUID absolutely?
Or you just want get a 'pseudo' universal unique ID for Java?

The MS GUID contains the informations in 128 bits:
1. MAC Address of LAN Card(if there is a LAN card on the host), or other Information of the host(It's a secret...)
2. time of creating the GUID

In Java, it's hard to get the first information. So we just use the IP Address or an random number to replace it.

public static String generateGUID() {
      long ip; //the 0-63th bit
      long t;  //the 64-127 bit
      try {
            ip=ip<<32 | ((long)(""+ipa[2]+ipa[3]).hashCode());
      } catch ( e) {
      String sip=Long.toHexString(ip);
      while (sip.length()<16)
      String st=Long.toHexString(t);
      while (st.length()<16)
      String ret=sip+st;
      return ret;

Of cause, this is not a perfact Java GUID, but you can make it better:
1. if you have no LAN Card on the host, you can use the informations(,user.home,...) to generate the first part of GUID
2. Mix the hashcode of IP(32 bits) with hashcode of, user.home,... (from System.getProperty ) (32 bits) to generate the first part of GUID
3. .... by your imagination

There are WINDOWS API functions for this purpose, for example CoCreateGUID();
Use JNI to declare a native methods in the class and then 'javah.exe' to generate the stubs. Then implement the calls with MSVC++ for example, and compile as a shared .dll.
From Java, you cannot do this directly :-)
GregLAuthor Commented:
I will reopen to see if there is an all java way.  If I don't get another answer diakov will get the points.
GregLAuthor Commented:
Thanks to all...
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.