Created
April 19, 2021 04:21
-
-
Save htr3n/edf78479d315c8c337722fc6bb2f5e88 to your computer and use it in GitHub Desktop.
Helper class to work with Java UUID
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.nio.ByteBuffer; | |
import java.nio.ByteOrder; | |
import java.util.UUID; | |
/** | |
* This class provides helper methods to work with UUID, for instance, converting UUID into 16-byte | |
* array for database column BINARY(16) and vice versa. | |
*/ | |
public final class UuidUtil | |
{ | |
private UuidUtil() | |
{ | |
} | |
/** | |
* Convert an {@link UUID} into a 16-byte array | |
* | |
* @param uuid the input {@link UUID} | |
* @return a 16-byte array if succeeded, otherwise {@code null} | |
*/ | |
public static byte[] asBytes(final UUID uuid) | |
{ | |
if (uuid != null) | |
{ | |
ByteBuffer bb = ByteBuffer.wrap(new byte[16]) | |
.order(ByteOrder.BIG_ENDIAN) // BIG_ENDIAN is the default, explicitly set it. | |
.putLong(uuid.getMostSignificantBits()) | |
.putLong(uuid.getLeastSignificantBits()); | |
byte[] bytes = bb.array(); | |
bb.clear(); | |
bb = null; | |
return bytes; | |
} | |
return null; | |
} | |
public static UUID asUuid(final byte[] bytes) | |
{ | |
if (bytes != null) | |
{ | |
ByteBuffer bb = ByteBuffer.wrap(bytes); | |
long firstLong = bb.getLong(); | |
long secondLong = bb.getLong(); | |
bb = null; | |
return new UUID(firstLong, secondLong); | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment