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 {
}