在Java中创建GUID的一些最佳方法是什么?


当前回答

用一个例子来扩展Mark Byers的回答:

import java.util.UUID;

public class RandomStringUUID {
    public static void main(String[] args) {
        UUID uuid = UUID.randomUUID();
        System.out.println("UUID=" + uuid.toString() );
    }
}

其他回答

看看与Java 5及更高版本捆绑在一起的UUID类。

例如:

如果你想要一个随机的UUID,你可以使用randomUUID方法。 如果您希望将UUID初始化为特定的值,可以使用UUID构造函数或fromString方法。

java.util.UUID.randomUUID();

其他答案都是正确的,尤其是斯蒂芬·C的这个答案。

走出Java

出于安全考虑,在Java中生成UUID值仅限于版本4(随机)。

如果你想要其他版本的uuid,一种方法是让你的Java应用程序通过调用JVM之外的方法来生成uuid:

Command-line utilityBundled with nearly every operating system. For example, uuidgen found in Mac OS X, BSD, and Linux. Database serverUse JDBC to retrieve a UUID generated on the database server.For example, the uuid-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 ServiceFor example, UUID Generator creates Versions 1 & 3 as well as nil values and GUID.

用一个例子来扩展Mark Byers的回答:

import java.util.UUID;

public class RandomStringUUID {
    public static void main(String[] args) {
        UUID uuid = UUID.randomUUID();
        System.out.println("UUID=" + uuid.toString() );
    }
}

这取决于你想要什么样的UUID。

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 construct UUID instances from long, byte[] or String 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.

关于UUID类型和变体的更多信息,维基百科中有一个很好的总结,RFC 4122和其他规范中有详细的信息。