1

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?

Igor G.
  • 6,955
  • 6
  • 26
  • 26

3 Answers3

1

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

 org.springframework.core.convert.support.DefaultConversionService
Igor G.
  • 6,955
  • 6
  • 26
  • 26
0

According to what you describe, if you have:

String var = "variable";
Class<?> type = Class.forName("your_class");// Your type
Object o = type.cast(var);

Now 3 things can happen:

  • o should be of your_class type
  • If var is null, o will be null or
  • ClassCastException will be thrown
rocketboy
  • 9,573
  • 2
  • 34
  • 36
  • Kinda, _var_ holds value, lets say "123" and type is Long. This code always throws ClassCastException. – Igor G. Jul 26 '13 at 10:22
  • "123" cannot be casted to Long or Integer for that matter. That is why we have functions like atoi and itoa. Is your expectation valid? – rocketboy Jul 26 '13 at 11:42
0
public class Sample {

    /**
     * @param args
     */
    public static void main(String[] args) {

        List<Class<?>> classList= new ArrayList<Class<?>>();
        classList.add(String.class);
        classList.add(Double.class);
        try {
            Class<?> myClass = Class.forName("java.lang.Double");
            //Object newInstance = myClass.newInstance();           

            for (Object object : classList) {               
                if(myClass.equals(object)){
                    //do what you like here
                    System.out.println(myClass);
                }

            }

        } catch (ClassNotFoundException e) {

        }
    }

}
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64