JavaSE 反射 Part4,javase反射part4
分享于 点击 33083 次 点评:153
JavaSE 反射 Part4,javase反射part4
原作者:尚硅谷-佟刚
package com.atweihai.reflection;
public class PersonDao extends Dao<Person> {
}
package com.atweihai.reflection;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class Dao<T> {
private Class<T> clazz;
public Dao() {
//获取Dao子类的带泛型参数的父类 com.atweihai.reflection.Dao<com.atweihai.reflection.Person>
Type type=this.getClass().getGenericSuperclass();
//获取具体的泛型参数
if(type instanceof ParameterizedType){
//强转成带参数的父类类型 com.atweihai.reflection.Dao<com.atweihai.reflection.Person>
ParameterizedType parameterizedType=(ParameterizedType) type;
//获取实际的泛型参数 对应的Class 数组 [class com.atweihai.reflection.Person]
Type[] args=parameterizedType.getActualTypeArguments();
//得到Class<T> 类型的 class
if(args!=null&&args.length>0){
Type arg=args[0];
if(arg instanceof Class){
clazz=(Class<T>) arg;
}
}
}
}
T get(Integer id){
System.out.println(clazz);
return null;
}
void save(T entity){
}
}
测试代码
@Test
public void testGenericAndReflection(){
PersonDao personDao=new PersonDao();
personDao.get(1);
}
相关文章
- 暂无相关文章
用户点评