Recently started to do a project, the project environment is spring4.2,struts2.3.1,hibernate4.3.0 .... Everything is configured properly, all the Pojo classes are well arranged. The service layer and the DAO layer were also extracted, but during the test, it was reported as a mistake, Java.lang.ClassCastException:java.lang.Class cannot be cast to Java.lang.reflect.ParameterizedType,,, debugging for a long time, have not found a way, and then read the Woshisap great God's blog to solve the problem, so paste the code of the Great God:
Class<t> Entityclass = (class<t>) ((Parameterizedtype) GetClass (). Getgenericsuperclass ()). Getactualtypearguments () [0];
Appears: Java.lang.ClassCastException:java.lang.Class cannot is cast to java.lang.reflect.ParameterizedType use the following tool class method to get
1 PackageCn.pconline.prolib.util;2ImportJava.lang.reflect.ParameterizedType; 3ImportJava.lang.reflect.Type; 4 5 Public classGenericsutils {6/**7 * The type of the pattern parameter of the parent class declared when the class is defined by reflection. 8 * If public Bookmanager extends genricmanager<book> 9 *@paramclazz the class to Introspect *@returnthe first generic declaration, or <code>Object.class</code> if cannot be determined*/13 Public Staticclass Getsuperclassgenrictype (class Clazz) {14returnGetsuperclassgenrictype (clazz, 0); 15 } 16 17/**18 * The type of the pattern parameter of the parent class declared when the class is defined by reflection. 19 * If public Bookmanager extends genricmanager<book> *@paramClazz Clazz The class to Introspect *@paramindex The index of the generic Ddeclaration,start from 0. at*/24 Public StaticClass Getsuperclassgenrictype (class Clazz,intIndexthrowsindexoutofboundsexception {Gentype Type =Clazz.getgenericsuperclass (); 27 28if(! (GentypeinstanceofParameterizedtype)) { 29returnObject.class; 30 } Type[] params =((Parameterizedtype) gentype). Getactualtypearguments (); 33 34if(Index >= params.length | | Index < 0) { 35returnObject.class; 36 } 37if(! (Params[index]instanceofClass)) { 38returnObject.class; 39 } 40return(Class) Params[index]; 41 } 42}
Finally, type the following code where you want to call:
class<t> Entityclass = Genericsutils.getsuperclassgenrictype (basicservice.class, 0);
Exception:java.lang.ClassCastException:java.lang.Class cannot is cast to Java.lang.reflect.ParameterizedType