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