不经意间看到的代码,为了说明问题,仿写了一个
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
class MSGC_OPTION {
}
public class GenericDAO<T> {
private Class<T> entityClass;
protected GenericDAO() {
Type superClass = getClass().getGenericSuperclass();
if (superClass instanceof Class<?>) { // sanity check, should never happen
throw new IllegalArgumentException("Internal error: TypeReference constructed without actual type information");
}
Type trueType = ((ParameterizedType)superClass).getActualTypeArguments()[0];
this.entityClass = (Class<T>)trueType;
}
public static void main(String[] args) throws Exception {
OptionManager manager = new OptionManager();
//GenericDAO<MSGC_OPTION> genericDAO = new GenericDAO<MSGC_OPTION>();
}
}
class OptionManager extends GenericDAO<MSGC_OPTION> {
}
我的问题就是
if (superClass instanceof Class<?>) { // sanity check, should never happen
throw new IllegalArgumentException("Internal error: TypeReference constructed without actual type information");
}
这个if为什么为false呢?
Class<?>通配符不是应该可以匹配所有Class吗,这里不是很清楚,求指教,谢谢!
------解决方案--------------------
昨天有点忙,没回复楼主,今天有点时间,就帮楼主彻底解决这个疑问,
OptionManager manager = new OptionManager();manager 这个对象如果加泛型,则
Type superClass = getClass().getGenericSuperclass();这句代码获取的是ParameterizedType这个接口的实现实例,而这个接口不是class的子类,所以if里是false,可以获取trueType--即泛型,也就是实际的代码中的参数。但是如果不加泛型,则if里会是true,这时候会抛出异常,因为这时候的superClass就是GenericDAO的对象,也就是加了泛型后的ParameterizedType这个接口的rawType这个属性。上次没看明白楼主的意思,这样子解释楼主应该可以理解了吧。