java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
clazz = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
java 泛型报java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType 错误。
java中的泛型采用擦拭法。无法得到自己本身的泛型。而调用getGenericSuperclass()方法得到的是父类的泛型。但如果有多重继承则需要遍历获取泛型定义。
Class c = getClass(); ParameterizedType ptype = null; do{ //遍历所有超类,直到找泛型定义 try { ptype = (ParameterizedType) c.getGenericSuperclass(); } catch (Exception e) { } c = c.getSuperclass(); }while(ptype==null && c!=null); if(ptype == null){ throw new PersistentNotSetException("子类中没有定义泛型的具体类型"); } this.persistentClass = (Class<T>) ptype.getActualTypeArguments()[0];
发现while 循环体内,catch块 只执行了一次。 将c = c.getSuperclass(); 放到循环体内将会是一个死循环