反射_泛型

/**
*在父类使用泛型的情况下,怎样得到子类传进来的是什么类型呢。
*看下面一个例子
*/


/**
*父类dao.java
*/
package com.chj.dao;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class Dao<T>
{
public Dao()
{ //创建子类时调用父类的构造器,所以this指向子类
System.out.println(this);
System.out.println(this.getClass());
/*
*得到子类带参数类型的父类
*public Type getGenericSuperclass()
*返回表示此 Class 所表示的实体(类、接口、基本类型或 void)的直接超类的 Type。 
*如果超类是参数化类型,则返回的 Type 对象必须准确反映源代码中所使用的实际类型参数。
*/
Type type = this.getClass().getGenericSuperclass();
System.out.println(type);
Class clazz = null;
//这个类型是否带参数
if(type instanceof ParameterizedType){
ParameterizedType parameterizedType = (ParameterizedType)type;
//Type[] getActualTypeArguments() 
//返回表示此类型实际类型参数的 Type 对象的数组。 
Type[] args = parameterizedType.getActualTypeArguments();
if(args != null && args.length > 0){
//得到子类传进来的这个参数类型
Type type1 = args[0];
if(type1 instanceof Class){
clazz = (Class<T>)type1;
}
}
}
System.out.println(clazz);
}
}


/**
*子类PersonDao 继承父类Dao 传进泛型参数Person
*/
package com.chj.dao;
public class PersonDao extends Dao<Person>{}


//Person类
package com.chj.dao;
public class Person{}


//测试类
package com.chj.dao;
import org.junit.Test;
public class TestDao
{
@Test
public void test(){
PersonDao personDao = new PersonDao();
}
}




输出:
com.chj.dao.PersonDao@14514713
class com.chj.dao.PersonDao
com.chj.dao.Dao<com.chj.dao.Person>
class com.chj.dao.Person


/**
* 根据以上原理写一个工具类
* 通过反射,获得定义Class时声明的父类的泛型参数的类型
* 如:public EmployeeDao extends BaseDao<Employee,String>
* @param clazz
* @param index
* @return
*/
public static Class getSuperClassGenricType(Class clazz,int index){
Type genType = clazz.getGenericSuperclass();

if(!(genType instanceof ParameterizedType)){
return Object.class;
}
Type [] params = ((ParameterizedType)genType).getActualTypeArguments();
if(index >= params.length || index < 0){
return Object.class;
}

if(!(params[index] instanceof Class)){
return Object.class;
}

return (Class)params[index];
}

@Test
public void testGetSuperClassGenricType(){
Class clazz = EmployeeDao.class;
Class argClazz = getSuperClassGenricType(clazz,0);
System.out.println(argClazz);
argClazz = getSuperClassGenricType(clazz,1);
System.out.println(argClazz);
}
输出:
class com.chj.dao.Employee
class java.lang.String
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值