Last active
September 13, 2016 16:14
-
-
Save zortax/9cfbd7f34769052c9a6a9f049cb9eed6 to your computer and use it in GitHub Desktop.
Simple Javamethod to convert a string to any primitive datatype (excluding char and String), may work with other datatypes if parse-method exists
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
public static <T> T stringToPrimitive(String str, Class<T> type) { | |
Method[] methods = type.getMethods(); | |
for (Method m : methods) { | |
if (m.getName().startsWith("parse") && m.getParameters().length == 1 && m.getParameterTypes()[0].equals(String.class)) { | |
try { | |
return (T) m.invoke(null, str); | |
} catch (IllegalAccessException | InvocationTargetException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment