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?
How about enums?
Your method can have a single line of code:
Testing with different classes:
The output:
If those are your only types of examples, then you can also do something like:
More information may provide for better answers. I'd be very much surprised if there isn't already some utility code out there that meets your specifications. There are a few ways to tackle this problem depending on the actual requirements.
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, andString
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.To convert from an Object (here a String) to another one, you can use transmorph :
NumberUtils.createNumber(str)
(from apache commons-lang)It decides what type of number to create, so you don't pass the class.