java 利用反射获取类,实例化,并执行其内部方法

时间:2021-02-06 19:38:57
@Test
	public void test1() throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{
		
		ClassLoader loader = Thread.currentThread().getContextClassLoader();
		Class<?> clazz = loader.loadClass("com.saber.model.Person");
		//获取无参构造器
		Constructor<?> cons = clazz.getDeclaredConstructor();
		//获取有参构造器,根据参数类型。
		Constructor<?> cons1 = clazz.getDeclaredConstructor(String.class, String.class);
		//实例化
		Person person = (Person) cons.newInstance();
		Person person1 = (Person) cons1.newInstance("saber", "beijing");
		
		//利用反射获取方法
		Method setName = clazz.getDeclaredMethod("setName", String.class);
		//执行方法
		setName.invoke(person, "saber");
		
		System.out.println(person.getName());
		System.out.println(person1);
	}