62,620
社区成员
发帖
与我相关
我的任务
分享
public class Person<T> {
public T age;
public Person(T age) { this.age = age; }
}
public class Student extends Person<Integer> {
public Student(Integer age) { super(age); }
}
public class ReflectDemo {
public static void main(String[] args) throws Exception {
List<Student> stu = fun(Student.class, "1,2");
System.out.println(stu);
}
public static <T> List<T> fun(Class<T> clazz, String seriable) throws Exception {
//试图通过反射创建两个student对象
List<T> stus = new ArrayList<>();
String[] ages = seriable.split(",");
for (String age : ages) {
//下面这句是否能不写Integer.class,而是通过clazz反射获得,但是我怎么获取都是Object类型
T stu = clazz.getDeclaredConstructor(Integer.class).newInstance(Integer.valueOf(age));
stus.add(stu);
}
return stus;
}
}
/**
* 获取泛型Class信息
*
* @return
*/
public Class<?> getClassType(Class clazz,int pos) {
Type type = clazz.getGenericSuperclass();
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
Type[] genericTypes = parameterizedType.getActualTypeArguments();
if (genericTypes.length >= pos + 1) {
return (Class<?>) genericTypes[pos];
}
}
return null;
}
public class Person<E> {
private E age;
private String name;
public Person(E age) {
this.age = age;
}
public E getAge() {
return age;
}
public void setAge(E age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@SuppressWarnings("unchecked")
public <T extends Person<E>> T fun(Class<T> tClass) {
try {
Type type = tClass.getGenericSuperclass();
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
Type[] types = parameterizedType.getActualTypeArguments();
return tClass.getDeclaredConstructor((Class<E>) types[0]).newInstance(9999);
}
}catch (Exception e) {
e.printStackTrace();;
}
return null;
}
}
