@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);
}
java 利用反射获取类,实例化,并执行其内部方法
最新推荐文章于 2022-12-15 22:45:00 发布