利用反射机制,使得list中可以存放不同类型的对象

首先建立一个泛型为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=男]]
发布了41 篇原创文章 · 获赞 1 · 访问量 1865

猜你喜欢

转载自blog.csdn.net/qq_38087131/article/details/105289949