也可以说是泛型与反射获取实力的两种方法
package demo5;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class DAO<T> {
Class<T> clazz;
public DAO(){
System.out.println("DAO的构造器被调用");
Type type = this.getClass().getGenericSuperclass();
//判断类型是否为带泛型的类型ParameterizedType
if(type instanceof ParameterizedType){
ParameterizedType parameterizedType = (ParameterizedType) type;
Type t = parameterizedType.getActualTypeArguments()[0];
clazz = (Class<T>) t;
}
}
public void set(T t){
}
public T get() throws Exception{
return clazz.newInstance();
}
public <E> E method(Class<E> t) throws Exception{
return t.newInstance();
}
}
package demo5;
import demo4.Person;
public class PersonDao extends DAO<Person>{
}
package demo4;
public class Person {
private String name;
privat