use ParameterizedType in the class to get the generic class of the entity class of the class
has the following code:
public class Demo<T> {
private Class<T> clazz;
public T getDemo() throws InstantiationException, IllegalAccessException{
return clazz.newInstance();
}
public static void test() throws InstantiationException, IllegalAccessException{
String str = new Demo<String>().getDemo();
}
}
now I"m going to call the test () method to get a String entity class, but when I call it, I throw a NullPointerException indicating that clazz is null and cannot be called. So at this point I"ll change the getDemo method, use ParameterizedType to get the generics and assign
public T getDemo() throws InstantiationException, IllegalAccessException{
Type superClass = getClass();
if(superClass instanceof ParameterizedType){
Type type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
this.clazz = (Class<T>) type;
}else{
System.out.println("");
}
return clazz.newInstance();
}
but the superClass obtained at this time is Demo, not Demo < String >, so the superClass instanceof ParameterizedType is not valid, the console output is "not equal", and the clazz is still not null, so I would like to ask you how to get generic classes in this case.
Note that it is useless to change Type superClass = getClass (); to Type superClass = getClass (). GetGenericSuperclass ();, because the Demo class does not inherit other classes, so getting Object, is not equal.