import java.security.SecureRandom; import java.util.UUID; /** * 封裝各類生成惟一性ID算法的工具類. */ public abstract class Identities { private static SecureRandom random = new SecureRandom(); /** * 封裝JDK自帶的UUID, 經過Random數字生成, 中間有-分割. */ public static String uuid() { return uuid(true); } /** * 封裝JDK自帶的UUID, 經過Random數字生成, 中間無-分割. */ public static String uuid(boolean hasPrefix) { String uuid = UUID.randomUUID().toString(); if (!hasPrefix) { uuid = uuid.replaceAll("-", ""); } return uuid; } /** * 使用SecureRandom隨機生成Long. */ public static long getLong() { return Math.abs(random.nextLong()); } /** * 基於Base62編碼的SecureRandom隨機生成bytes. */ public static String getBase62(int length) { byte[] randomBytes = new byte[length]; random.nextBytes(randomBytes); return Encodes.encodeBase62(randomBytes); } }