在已知类或者对象的情况下,很容易获得他的实际类型
- 对象getClass();
- 类.class
但是如果是泛型的情况下,如何获取它的实际类型呢??直接上代码
package pac01;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Date;
import java.util.Vector;
/**
* 测试通过反射获取泛型类的实际类型
* 获取Vector中Date的实际类型
* @author acer
* @param <T>
* @param <T>
*/
public class Test {
public static void main(String []args) throws NoSuchMethodException, SecurityException {
Method method = Test.class.getMethod("applyVector", Vector.class);
Type [] types = method.getGenericParameterTypes();
ParameterizedType ptype = (ParameterizedType) types[0];
//得到原始的类型
System.out.println(ptype.getRawType());
//得到实际化的类型参数
System.out.println(ptype.getActualTypeArguments()[0]);
}
public static void applyVector(Vector<Date> v2) {
}
}