赞
踩
我们在开发的过程中可能需要随机生成一个ID,例如数据库中的某个ID
有时候也要对其进行校验。
UUID,是Universally Unique Identifier的缩写,UUID出现的目的,是为了让分布式系统可以不借助中心节点,就可以生成UUID来标识一些唯一的信息。
-
- import java.util.UUID;
-
- public class UUIDTest {
-
- public static void main(String[] args) {
- String uuid1 = "e65deb4c-a110-49c8-a4ef-6e69447968d6";
- String uuid2 = "ca4a8a92-d4ed-4fc4-8a4f-345c587fbdcb";
- String uuid3 = "e1f15f1d-6edb-4f70-8a05465se273eaf95a";
- System.out.println("check > " + uuid1 + " > " + isValidUUID(uuid1));
- System.out.println("check > " + uuid2 + " > " + isValidUUID(uuid2));
- System.out.println("check > " + uuid3 + " > " + isValidUUID(uuid3));
- System.out.println("build a uuid> " + getRandomUUID(null));
- System.out.println("build a uuid> " + getRandomUUID(null));
- System.out.println("build a uuid> " + getRandomUUID("kangyucheng"));
- System.out.println("build a uuid> " + getRandomUUID("kangyucheng"));
-
- }
-
- public static boolean isValidUUID(String uuid) {
- // UUID校验
- if (uuid == null) {
- System.out.println("uuid is null");
- }
- String regex = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$";
- if (uuid.matches(regex)) {
- return true;
- }
- return false;
- }
-
- public static UUID getRandomUUID(String str) {
- // 产生UUID
- if (str == null) {
- return UUID.randomUUID();
- } else {
- return UUID.nameUUIDFromBytes(str.getBytes());
- }
- }
- }

check > e65deb4c-a110-49c8-a4ef-6e69447968d6 > true check > ca4a8a92-d4ed-4fc4-8a4f-345c587fbdcb > true check > e1f15f1d-6edb-4f70-8a05465se273eaf95a > false build a uuid>93ce6775-bc89-4849-8ae9-fb305c909700 build a uuid>7a61f2e0-903b-4904-b2bd-a075b19adb8c build a uuid>8b68aa00-6a79-3cbb-996f-780f464f3aae build a uuid>8b68aa00-6a79-3cbb-996f-780f464f3aae |
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。