I am trying to write a general method to parse objects from strings. To be clear, I have the following not-so-elegant implementation:
public static Object parseObjectFromString(String s, Class class) throws Exception {
String className = class.getSimpleName();
if(className.equals("Integer")) {
return Integer.parseInt(s);
}
else if(className.equals("Float")) {
return Float.parseFloat(s);
}
else if ...
}
Is there a better way to implement this?
Your method can have a single line of code:
Testing with different classes:
The output: