首先建立一个泛型为Integer的list。随后利用反射机制使list中存放一个student对象
辅助类 Student
public class Student {
private int id;
private String name;
//getters and setters and toString
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
测试类 :实现该功能
public class Test {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
//获取并初始化一个student对象,此处使用反射机制来实例化一个student对象
Class obj=Class.forName("com.hy.test.Student");
Student student = (Student)obj.newInstance();
student.setId(2);
student.setName("男");
//初始化一个泛型为Integer的list并添加两个元素
List<Integer> list=new ArrayList<Integer>();
list.add(1);
list.add(2);
//利用反射后去list的类型
Class<? extends Object> clazz=list.getClass();
//获取list的add方法
Method method = clazz.getMethod("add",Object.class);
//调用list的add方法,将student对象存入list中
method.invoke(list, student);
System.out.println(list);
}
}
运行结果:
[1, 2, Student [id=2, name=男]]