introduction
UUID (Universally Unique Identifier) is a 128-bit identifier that can uniquely identify information. It is widely used in database primary keys, unique identification in distributed systems, file naming and other scenarios. The generation of UUIDs follows certain standards, which ensures that the UUID generated at different times and places is unique. In Java, the generation of UUID isClass provided. In order to simplify the generation and use of UUIDs, a UUID generation tool class can be encapsulated-
UUIDUtils
, provides convenient interfaces to generate different types of UUIDs. This article will introduce how to build a feature-richUUIDUtils
Tools and display their application in actual development.
Basic concepts of UUID
The UUID standard defines multiple versions, including commonly used version 1 (based on timestamps and nodes), version 3 (based on namespace MD5 hash), version 4 (based on random numbers), version 5 (based on namespace SHA-1 hash), etc. Java'sUUID
The class mainly supports versions 3, 4 and 5.
The format of UUID is usually 32-bit hexadecimal digits, separated into five segments by hyphen, and the shape is like:550e8400-e29b-41d4-a716-446655440000
。
UUIDUtils Tool Class Design
UUIDUtils
is a tool class for generating and processing UUIDs. In order to meet the needs of different scenarios,UUIDUtils
Provides the following main functions:
- Generate standard UUID (version 4): Generate a random standard UUID.
- Generate a UUID without hyphen: Generate a UUID string that removes hyphen.
- Generate a UUID based on namespace (version 3 and version 5): Generate UUID based on the specified namespace and name.
- UUID verification: Check whether the string is in a valid UUID format.
- Format UUID: Add or remove hyphen of UUID as needed.
The following isUUIDUtils
Implementation of tool classes:
import ; import ; public class UUIDUtils { // Regular expressions in UUID format private static final Pattern UUID_PATTERN = ("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"); // Namespace UUID (can be any UUID, here is a common namespace UUID example) private static final UUID NAMESPACE_DNS = ("6ba7b810-9dad-11d1-80b4-00c04fd430c8"); // Generate standard UUID (version 4) public static String generateUUID() { return ().toString(); } // Generate UUID without hyphen public static String generateUUIDWithoutHyphens() { return ().toString().replace("-", ""); } // Generate a UUID based on namespace (version 3, based on MD5 hash) public static String generateUUIDv3(String name) { return (()).toString(); } // Generate a UUID based on namespace (version 5, based on SHA-1 hash) public static String generateUUIDv5(String name) { return generateUUIDv5(NAMESPACE_DNS, name); } // Generate UUID based on the specified namespace (version 5, based on SHA-1 hash) public static String generateUUIDv5(UUID namespace, String name) { return ((() + name).getBytes()).toString(); } // Check whether it is a valid UUID format public static boolean isValidUUID(String uuid) { return uuid != null && UUID_PATTERN.matcher(uuid).matches(); } // Remove hyphens in UUID public static String removeHyphens(String uuid) { return uuid != null ? ("-", "") : null; } // Format UUID and add hyphen public static String addHyphens(String uuid) { if (uuid == null || () != 32) { throw new IllegalArgumentException("Invalid UUID format without hyphens"); } return (0, 8) + "-" + (8, 12) + "-" + (12, 16) + "-" + (16, 20) + "-" + (20); } }
Method details
-
Generate standard UUID (version 4):
-
generateUUID()
: Use Java built-in()
The method generates a random UUID (version 4) with a hyphen.
-
-
Generate a UUID without hyphen:
-
generateUUIDWithoutHyphens()
: Generate standard UUIDs and remove hyphens from them, suitable for scenarios where compact UUID format is required.
-
-
Generate a namespace-based UUID (version 3 and version 5):
-
generateUUIDv3(String name)
: Generate UUID based on MD5 hashing algorithm and specified name (version 3) for unique identifiers related to namespace. -
generateUUIDv5(String name)
: Generate UUID based on SHA-1 hashing algorithm and specified names (version 5), which has stronger uniqueness. -
generateUUIDv5(UUID namespace, String name)
: Allows UUID generation of a specified namespace (version 5).
-
-
UUID verification:
-
isValidUUID(String uuid)
: Use regular expressions to check whether the string is in a valid UUID format.
-
-
Format UUID:
-
removeHyphens(String uuid)
: Removes hyphens in UUID and returns a compact UUID string. -
addHyphens(String uuid)
: Format compact UUID strings into standard UUID format with hyphen.
-
Practical application examples
public class UUIDUtilsExample { public static void main(String[] args) { // Generate standard UUID String uuid = (); ("Standard UUID: " + uuid); // Generate UUID without hyphen String uuidWithoutHyphens = (); ("UUID without hyphens: " + uuidWithoutHyphens); // Generate a UUID based on a namespace (version 3) String uuidV3 = UUIDUtils.generateUUIDv3(""); ("UUID v3 (namespace-based): " + uuidV3); // Generate a UUID based on a namespace (version 5) String uuidV5 = UUIDUtils.generateUUIDv5(""); ("UUID v5 (namespace-based): " + uuidV5); // Verify UUID format boolean isValid = (uuid); ("Is valid UUID: " + isValid); // Remove hyphens in UUID String compactUUID = (uuid); ("Compact UUID: " + compactUUID); // Add hyphen to compact UUID String formattedUUID = (compactUUID); ("Formatted UUID: " + formattedUUID); } }
Advantages of UUIDUtils
- Simplify UUID operations: By encapsulating UUID generation and processing functions, boilerplate code is reduced, and developers do not need to deal with underlying details.
- flexibility: Supports generation of multiple UUID versions (versions 3, 4 and 5), which can meet the unique identification requirements of different scenarios.
- Format conversion: Provides UUID format conversion function (add or remove hyphen) to meet the requirements of different applications for UUID format.
- Easy to expand: More UUID related features can be easily added, such as time-based UUID generation or support for custom namespaces.
Expansion and improvement
- Custom namespace support: Allows users to customize namespace UUIDs to better support diverse namespace requirements.
- Performance optimization: For high-frequency UUID generation scenarios, cache namespaces or optimize string operations can be considered.
- Convert UUID to other formats: Supports converting UUIDs to more compact encoding formats (such as Base64) for reducing storage or transfer lengths.
- Time-related UUID: Implement time stamp-based UUID generation and provide sorting function.
in conclusion
UUIDUtils
Tools provide a simple, flexible and efficient UUID operation interface by encapsulating common functions of UUID generation and processing, greatly simplifying UUID operations in Java applications. Whether it is generating a standard UUID, removing hyphen, or a namespace-based UUID,UUIDUtils
All can provide strong support. Through continuous expansion and improvement,UUIDUtils
Can meet the needs of more complex application scenarios and become a right-hand assistant for developers when dealing with UUIDs.
Summarize
There is a class in Java called UUID, which can be used to generate unique identifiers. For convenience, we can create a UUIDUtils tool class to encapsulate the generation logic of UUID.
First, we need to import the class. Then, in the UUIDUtils class, we can define a static method to generate the UUID. This method should return a UUID represented by a string.
Before generating the UUID, we can use the randomUUID method of the UUID class to create a new UUID object. We can then use the toString method to convert the UUID to a string representation.
Finally, we can call the static method of the UUIDUtils class where we need to generate the UUID and store the string value it returns into a variable for subsequent use.
Unique identifiers generated using UUIDs can be used for various purposes, such as storing unique identifiers for records in a database, or unique identifiers for generating file names, etc.
This is the end of this article about UUID generation tool class (UUIDUtils) in java. For more related contents of UUID generation tool class UUIDUtils, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!