43 通过反射获得泛型的实际类型参数

 

 

public static void applyVector(Vector<Date> v1){}
Method meth=GenericTest.class.getMethod("applyVector", Vector.class);
		Type[] types=meth.getGenericParameterTypes();
		ParameterizedType pys=(ParameterizedType) types[0];//ParameterizedType类型是Tpye类型其中之一的儿子
		System.out.println(pys.getRawType());//得到她的原始类型//class java.util.Vector
		System.out.println(pys.getActualTypeArguments()[0]);//得到实际的类型参数,注意他是个数组,因为他可能有多个,例如HashMap<K,V>//class java.util.Vector

 

 

l  示例代码:

 

	Class GenericalReflection {
		  private Vector<Date> dates = new Vector<Date>();
		  public void setDates(Vector<Date> dates) {
		    this.dates = dates;
		  }
		  public static void main(String[] args) {
		   Method methodApply = GenericalReflection.class.getDeclaredMethod("applyGeneric", Vector.class);
		   ParameterizedType pType = (ParameterizedType)
		                    (methodApply .getGenericParameterTypes())[0];
		            System.out.println("setDates("
		                    + ((Class) pType.getRawType()).getName() + "<"
		                    + ((Class) (pType.getActualTypeArguments()[0])).getName()
		                    + ">)" );
		  }
	}

 

 

l  泛型DAO的应用:

Ø  public abstract class DaoBaseImpl<T> implements DaoBase<T> {

 

       protected Class<T> clazz;

       public DaoBaseImpl() {

              Type type = this.getClass().getGenericSuperclass();

              ParameterizedType pt = (ParameterizedType) type;

              this.clazz = (Class) pt.getActualTypeArguments()[0];

              System.out.println("clazz = " + this.clazz);

       }

      }

Ø  public class ArticleDaoImpl extends DaoBaseImpl<Article> implements ArticleDao {

       }

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值