編輯:對不起,我提供下面的例子不會重現問題...我試圖找到正確的方式來重現它。在此之前,你可以不理會我的問題...反射無法獲得覆蓋泛型類型接口的方法的實際參數類型?
通常我們搶的方法的參數類型是這樣的:
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