- 泛型类取得泛型Class对象
1)在类上的泛型
import java.lang.reflect.ParameterizedType;
public class Generic<T> {
@SuppressWarnings("unchecked")
public Class<T> getCls() {
return (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
public static void main(String[] args) {
//注意一下代码,创建的是Generic的之类的对象,相当于把Integer传给Generic,这
//样getGenericSuperclass()).getActualTypeArguments()[0]才不出错
System.out.println(new Generic<Integer>() {
}.getCls());
System.out.println(new Generic<Date>() {
}.getCls());
}
}
2)在方法上的泛型
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
public class Generic2 {
@SuppressWarnings("unchecked")
public <T> Class<T> getCls() {
return (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
public void printList(List<String> list) {
for (String s : list) {
System.out.println(s);
}
}
public static void main(String[] args) throws Exception {
Method m = Generic2.class.getMethod("printList", List.class);
for (Type paramType : m.getGenericParameterTypes()) {
if (paramType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) paramType;
Class<?> genericClazz = (Class<?>) (parameterizedType.getActualTypeArguments()[0]);
System.out.println(genericClazz);// 就是string
//调用new String(String s);构造方法
Constructor c = genericClazz.getDeclaredConstructor(String.class);
Object o = c.newInstance("abc12");
System.out.println(o);
}
}
}
}
- 调用带参数的构造函数
import java.lang.reflect.Constructor;
public class Employee {
private String name;
private String code;
public Employee(String name, String code) {
this.name = name;
this.code = code;
}
public String toString() {
return code + "," + name;
}
public static void main(String[] args) throws Exception {
Class<?> clzz = Class.forName("Employee");
Constructor<?> cntor = clzz.getDeclaredConstructor(String.class, String.class);
System.out.println(cntor.newInstance("张三", "A0001"));
System.out.println(cntor.newInstance("李四", "A0002"));
}
}