背景:
我们在开发的过程中可能需要随机生成一个ID,例如数据库中的某个ID有时候也要对其进行校验。
UUID:
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
以上所述是小编给大家介绍的java获取UUID与UUID的校验详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!