Conversion from string to generic type

只谈情不闲聊 提交于 2020-03-18 05:46:08

问题


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
        }
        ...
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/24589495/conversion-from-string-to-generic-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!