vendredi 4 mars 2016

Reflection can't get the actual parameter type of a method that overrides from a generic-typed interface?

EDIT: Sorry the example I provide below doesn't reproduce the problem... I'm trying to find the right way to reproduce it. Before that, you may just ignore my question...

Usually we grab the parameter type of a method like this:

Class<?> clazz = method.getParameterTypes()[0]

I have never thought twice about it before, but recently I bumped into an issue that I always got class java.lang.Object when doing that. After an inspection, I found out the case can be described like this:

/** A parameterized interface */
public interface IService<T> {

    Result create(T obj);
}

/** An implementation */
public class CarService implements IService<Car> {

    public Result create(Car car) { ... }
}

And then when I use the way above to get the class of the parameter car, it turns out to be a class java.lang.Object:

Method methods = CarService.class.getMethods();
for (Method method : methods) {
    Class<?>[] types = method.getParameterTypes();
    // when the loop meets "create" here ...
}

I guess I have totally forgot something very fundamental about type erase? But now I really need get the actual parameter type in this case, if it's possible...





Aucun commentaire:

Enregistrer un commentaire