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?

4
  • 1
    Show us the code, it is better understandable with lines of code Commented Jul 26, 2013 at 9:36
  • 1
    What I understood you want something like this stackoverflow.com/questions/8918550/… Commented Jul 26, 2013 at 9:43
  • 1
    Do you mean 'convert'? You can't cast a Java String to anything except the interfaces it implements. Commented Jul 26, 2013 at 10:30
  • That really looks like I am trying to convert, not cast. Commented Jul 29, 2013 at 15:06

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Kinda, var holds value, lets say "123" and type is Long. This code always throws ClassCastException.
"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?
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) {

        }
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.