动态执行某个类的某个方法

public static void main(String[] args) throws IOException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException, ClassNotFoundException {
//1、加载配置文件
//1.1创建Properties对象
Properties pro=new Properties();
//1.2加载配置文件,转换为一个集合
//1.2.1获取class目录下的配置文件
ClassLoader classLoader = DemoReflectTest.class.getClassLoader();
InputStream is= classLoader.getResourceAsStream("pro.properties")
pro.load(is);

//2.获取配置文件中定义的数据
String className=pro.getProperty("className");
String methodName=pro.getProperty("methodName");

//3.加载该类进内存
Class cls=Class.forName(className);
//4、创建对象
Object obj=cls.newInstance();
//5获取方法对象
Method method = cls.getMethod(methodName);
//4、执行方法
method.invoke(obj);

}
posted @ 2020-03-10 03:18  ☆♂安♀★  阅读(576)  评论(0编辑  收藏  举报