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:
public static <T> T parseObjectFromString(String s, Class<T> clazz) throws Exception {
return clazz.getConstructor(new Class[] {String.class }).newInstance(s);
}
Testing with different classes:
Object obj1 = parseObjectFromString("123", Integer.class);
System.out.println("Obj: " + obj1.toString() + "; type: " + obj1.getClass().getSimpleName());
BigDecimal obj2 = parseObjectFromString("123", BigDecimal.class);
System.out.println("Obj: " + obj2.toString() + "; type: " + obj2.getClass().getSimpleName());
Object obj3 = parseObjectFromString("str", String.class);
System.out.println("Obj: " + obj3.toString() + "; type: " + obj3.getClass().getSimpleName());
Object obj4 = parseObjectFromString("yyyy", SimpleDateFormat.class);
System.out.println("Obj: " + obj4.toString() + "; type: " + obj4.getClass().getSimpleName());
The output:
Obj: 123; type: Integer
Obj: str; type: String
Obj: 123; type: BigDecimal
Obj: java.text.SimpleDateFormat@38d640; type: SimpleDateFormat
I'm not sure what you're trying to do. Here's a few different guesses:
You should look into serialization. I use XStream, but writeObject and java.beans.XMLEncoder also works.
Usually, this means a problem with the user specification. What are you receiving from the user, and why would it be able to be so many different kinds?
In general, you will want the type to be as broad as possible: use double
if it's a number, and String
for almost everything else. Then build other things from that variable. But don't pass in the type: usually, the type should be very obvious.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With