Skip to content

Instantly share code, notes, and snippets.

@zortax
Last active September 13, 2016 16:14
Show Gist options
  • Save zortax/9cfbd7f34769052c9a6a9f049cb9eed6 to your computer and use it in GitHub Desktop.
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
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