Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion from string to generic type

I need to convert string to variable value. I found solution only for C#. I need it in Java.

public class Property<T> {

    T value;

    public void setValue(String input){
        if(value instanceof String){
           value= input; // value is type of T not type of string (compilation error)
                         // incompatible types: String cannot be converted to T
        }
        if(value instanceof int){
           //parse string
        }
        if(value instanceof boolean){
           //parse string
        }
        ...
    }
}
like image 785
SpeedEX505 Avatar asked Jul 05 '14 18:07

SpeedEX505


2 Answers

That is not how it works. You can, however, use polymorphism, to achieve a useful result.

Solution with polymorphism

Base generic (and abstract) property

public abstract class Property<T> {
    T value;
    public abstract void setValue(String input);
}

Property for Strings

public class StringProperty extends Property<String> {
    @Override
    public void setValue(String input) {
        this.value = input;
    }
}

Property for integers

public class IntegerProperty extends Property<Integer> {
    @Override
    public void setValue(String input) {
        this.value = Integer.valueOf(input);
    }
}

Not sure what your actual goal is, but this approach might work.

Note, that input instanceof T will fail, because of type erasure. It's not gonna work.


Solution with Class<T> as argument

To elaborate more on your approach, this would work - but it's UGLY.

Ugly and not very convenient. No idea why you'd want it, tbh.

class Property<T> {

    public T value;
    private final Class<T> clazz;

    public Property(Class<T> clazz) {
        super();
        this.clazz = clazz;
    }       

    @SuppressWarnings("unchecked")
    public void setValue(String input) {
        if (clazz.isAssignableFrom(String.class)) {
            value = (T) input;
        } else if (clazz.isAssignableFrom(Integer.class)) {
            value = (T) Integer.valueOf(input);
        } else if (clazz.isAssignableFrom(Boolean.class)) {
            value = (T) Boolean.valueOf(input);
        } else if (clazz.isAssignableFrom(Double.class)) {
            value = (T) Double.valueOf(input);
        } else {
            throw new IllegalArgumentException("Bad type.");
        }
    }
}

Used like so:

Property<String> ff = new Property<>(String.class);
ff.setValue("sdgf");

Property<Integer> sdg = new Property<>(Integer.class);
sdg.setValue("123");

System.out.println(ff.value);
System.out.println(sdg.value);

Solution with Reflection

Apparently, it's possible to figure out the parameter used to instantiate property.

This little magic formula gives you just that:

(Class<?>) getClass().getTypeParameters()[0].getBounds()[0]

I don't even know how I managed to find it. Well, here we go:

class Property<T> {

    T value;    

    @SuppressWarnings("unchecked")
    public void setValue(String input)
    {
        // BEHOLD, MAGIC!
        Class<?> clazz = (Class<?>) getClass().getTypeParameters()[0].getBounds()[0];

        if (clazz.isAssignableFrom(String.class)) {
            value = (T) input;
        } else if (clazz.isAssignableFrom(Integer.class)) {
            value = (T) Integer.valueOf(input);
        } else if (clazz.isAssignableFrom(Boolean.class)) {
            value = (T) Boolean.valueOf(input);
        } else if (clazz.isAssignableFrom(Double.class)) {
            value = (T) Double.valueOf(input); 
        } else {
            throw new IllegalArgumentException("Bad type.");
        }
    }
}

And don't look at me, I wouldn't use that. I have some common sense.

like image 50
MightyPork Avatar answered Oct 14 '22 14:10

MightyPork


I found a new way by using Spring.

public static <T> T convertJsonToObject(String json, Class<T> valueType) {
    try {
        return json != null ? new ObjectMapper().readValue(json, valueType) : null;
    } catch (Exception e) {
        return null;
    }
}
private static void processValidate(Class<?> valueClass, String value) {
     Object parsedValue = Utils.convertJsonToObject(value, valueClass);
     // logic
}
like image 39
Денис Бурмистров Avatar answered Oct 14 '22 12:10

Денис Бурмистров