Last active
December 15, 2016 05:47
-
-
Save varrix/14cdc08c96b8c5f5d08f to your computer and use it in GitHub Desktop.
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
/** | |
* Retrieve a UUID safely from a {@link String}. | |
* | |
* @param string The {@link String} to deserialize into an {@link UUID} object. | |
* @return {@link Optional#empty()} if the provided {@link String} is illegal, otherwise an {@link Optional} | |
* containing the deserialized {@link UUID} object. | |
*/ | |
public static Optional<UUID> getUUID(String string) { | |
if (string.contains("-")) { | |
try { | |
return Optional.of(UUID.fromString(string)); | |
} catch (IllegalArgumentException exc) { | |
return Optional.empty(); | |
} | |
} | |
String builder = string.substring(0, 8) + "-" | |
+ string.substring(8, 12) + "-" | |
+ string.substring(12, 16) + "-" | |
+ string.substring(16, 20) + "-" | |
+ string.substring(20, 32); | |
return Optional.of(UUID.fromString(builder)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment