编辑:对不起,我提供下面的例子不会重现问题...我试图找到正确的方式来重现它。在此之前,你可以不理会我的问题...反射无法获得覆盖泛型类型接口的方法的实际参数类型?
通常我们抢的方法的参数类型是这样的:
Class<?> clazz = method.getParameterTypes()[0]
我从来没有想过而后行之前,但最近我碰到了这个问题我总是得到class java.lang.Object
。检查后,我发现的情况下可以这样描述:
/** A parameterized interface */
public interface IService<T> {
Result create(T obj);
}
/** An implementation */
public class CarService implements IService<Car> {
public Result create(Car car) { ... }
}
,然后当我使用上面的方法来获取类的参数car
的,它原来是一个class java.lang.Object
:
Method methods = CarService.class.getMethods();
for (Method method : methods) {
Class<?>[] types = method.getParameterTypes();
// when the loop meets "create" here ...
}
我想我完全忘记了关于类型擦除的一些非常基本的东西?但现在我真的需要得到这种情况下的实际参数类型,如果可能的话...
尝试'method.getGenericParameterTypes()'而不是'方法.getParameterTypes()' – Ferrybig