Igor G. Igor G. - 1 year ago 59
Java Question

How to convert a string value to some concrete type?

I have a string value and a class object of a concrete type.

So my question is how to convert a string value to that type?

It really looks like the only possible way is to do something like this:

private Object convertTo(String value, Class type) {
if(type == long.class || type == Long.class)
return Long.valueOf(value);
if(type == int.class || type == Integer.class)
return Integer.valueOf(value);
if(type == boolean.class || type == Boolean.class)
return Boolean.valueOf(value);
return value;

But that looks ugly ... is there any nicer way to do that?

Answer Source

What I was really looking for is some sort of generic type conversion. The one that worked the most for me is from Spring:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download