jeudi 3 mai 2018

Java generic method and type erasure

I had an issue with a generic method result being passed to the method of the Reflection API. The method that is receiving this parameter is:

Method method = getMethod();
method.invoke(item,convertValue(value, someType);

The generic method looked like:

private <T> T convertValue(String value, Type type) {
    T converted=null;
    if (type == Type.INT) {
        converted = (T) Integer.valueOf(value);
    }
    return converted;
}

As it is now, it causes ClassCastException: java.lang.Integer cannot be cast to [Ljava.lang.Object. I found out that with some workarounds it works. My first variant was:

private <T> T convertValue(String value, Type type) {
    if (type == Type.INT) {
        return (T) Integer.valueOf(value);
    }
    return null;
}

And second one that also worked for me:

private <T> T convertValue(String value, Type type) {
    Object converted=null;
    if (type == Type.INT) {
        converted = Integer.valueOf(value);
    }
    return (T)converted;
}

Both variants work, but I can't understand what is the difference between them and what actually happens in the very first variant(the one that I had to fix). The reflection method calls the ordinary setter method that sets an Integer variable for an object.





Aucun commentaire:

Enregistrer un commentaire