Created
November 19, 2018 14:11
-
-
Save RChehowski/48e9f5a3b23588c73acb2ba9035e768a to your computer and use it in GitHub Desktop.
parse
This file contains hidden or 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
private static <T extends Number> Optional<T> parse(final String s, final Class<T> clazz) | |
{ | |
// Escape if null input | |
if ((s == null) || (clazz == null)) | |
return Optional.empty(); | |
Object parsed = null; | |
NumberFormatException exception = null; | |
try { | |
// Integral types | |
if (Byte.class.isAssignableFrom(clazz)) | |
parsed = Byte.parseByte(s); | |
else if (Short.class.isAssignableFrom(clazz)) | |
parsed = Short.parseShort(s); | |
else if (Integer.class.isAssignableFrom(clazz)) | |
parsed = Integer.parseInt(s); | |
else if (Long.class.isAssignableFrom(clazz)) | |
parsed = Long.parseLong(s); | |
// Floating point | |
else if (Float.class.isAssignableFrom(clazz)) | |
parsed = Float.parseFloat(s); | |
else if (Double.class.isAssignableFrom(clazz)) | |
parsed = Double.parseDouble(s); | |
// Big numbers | |
else if (BigInteger.class.isAssignableFrom(clazz)) | |
parsed = new BigInteger(s); | |
else if (BigDecimal.class.isAssignableFrom(clazz)) | |
parsed = new BigDecimal(s); | |
// Or else it will be null | |
} | |
catch (NumberFormatException e) { | |
exception = e; | |
} | |
if (parsed != null) | |
{ | |
if (clazz.isInstance(parsed)) | |
{ | |
@SuppressWarnings("unchecked") | |
final T t = (T)parsed; | |
return Optional.ofNullable(t); | |
} | |
else | |
{ | |
System.err.println("Error: " + parsed.toString() + " must be a kind of " + clazz.getName()); | |
} | |
} | |
else if (exception != null) | |
{ | |
System.err.println("Error: " + exception.getMessage() + ", unable to parse into " + clazz.getName()); | |
} | |
else | |
{ | |
System.err.println("Error: " + clazz.getName() + " extends Number, but cannot be processed"); | |
} | |
return Optional.empty(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment