public class UuidUtils { public static UUID asUuid(byte[] bytes) { ByteBuffer bb = ByteBuffer.wrap(bytes); long firstLong = bb.getLong(); long secondLong = bb.getLong(); return new UUID(firstLong, secondLong); } public static byte[] asBytes(UUID uuid) { ByteBuffer bb = ByteBuffer.wrap(new byte[16]); bb.putLong(uuid.getMostSignificantBits()); bb.putLong(uuid.getLeastSignificantBits()); return bb.array(); }}
@Testpublic void verifyUUIDBytesCanBeReconstructedBackToOriginalUUID() { UUID u = UUID.randomUUID(); byte[] uBytes = UuidUtils.asBytes(u); UUID u2 = UuidUtils.asUuid(uBytes); Assert.assertEquals(u, u2);}@Testpublic void verifyNameUUIDFromBytesMethodDoesNotRecreateOriginalUUID() { UUID u = UUID.randomUUID(); byte[] uBytes = UuidUtils.asBytes(u); UUID u2 = UUID.nameUUIDFromBytes(uBytes); Assert.assertNotEquals(u, u2);}