UUID Random Parse Roundtrip
Generate random UUIDv4 identifiers with randomUUID, parse canonical text back with fromString, and rely on fromString rejecting malformed input.
Code
import java.util.UUID;
public class IdempotencyKey {
public static void main(String[] args) {
// 随机 UUID(randomUUID):version 4,带固定版本/变体位
UUID key = UUID.randomUUID();
System.out.println("version: " + key.version() + " variant: " + key.variant());
// canonical 文本固定 36 字符(8-4-4-4-12)
String text = key.toString();
System.out.println("length: " + text.length());
// fromString 解析回对象:equals 与 toString 往返一致
UUID parsed = UUID.fromString(text);
System.out.println("roundtrip equals: " + parsed.equals(key));
// 非法串抛 IllegalArgumentException,而不是静默返回 null
try {
UUID.fromString("not-a-uuid");
} catch (IllegalArgumentException e) {
System.out.println("invalid input rejected");
}
}
}How the snippet works
The snippet is organized around the class IdempotencyKey and the function main.
Applying it
Running the file prints labeled results such as version:, length:, roundtrip equals: — each operation’s effect is visible in the output.
Statements that matter
UUID parsed = UUID.fromString(text);
UUID.fromString("not-a-uuid");
UUID key = UUID.randomUUID();
Interactive Tools for This Topic
UUID v4 GeneratorGenerate cryptographically random UUIDs version 4 using the Web Crypto API. Produce single or batch UUIDs with optional uppercase formatting and copy-to-clipboard support.Passphrase GeneratorGenerate memorable multi-word passphrases from a fixed 150-word list with crypto randomness, separators, and capitalization options.Password GeneratorGenerate random passwords from selectable character classes using crypto.getRandomValues with rejection sampling and class guarantees.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does UUID Random Parse Roundtrip print when run?
- The script runs standalone; its 4 labeled outputs include `version:`, `length:`, `roundtrip equals:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.