通过注解的方式与反射调用方法
public class Test02 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class<Test02> c = Test02.class;
Anno anno = c.getAnnotation(Anno.class);//获取当前类指定的注解对象
String className = anno.className();//获取指定的注解
String methodName = anno.methodName();//获取指定的注解
Class<?> c1 = Class.forName(className);//通过获取的注解获取目标类的字节码对象
Constructor<?> cons = c1.getConstructor();//得到目标类的构造方法
Object obj = cons.newInstance();//通过构造方法创建对象
Method method = c1.getMethod(methodName);//通过字节码对象得到目标类中的方法
method.invoke(obj);通过反射调用方法
}
}
通过配置文件与反射调用方法
public class Test {
public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Properties pro = new Properties();
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("run.properties");//
pro.load(is);//加载配置文件,可以将Properties看做一个集合,将加载到的配置文件以键值对的形式放在Properties集合中
String className = pro.getProperty("className");//通过键名获取值
String methodName = pro.getProperty("methodName");//通过键名获取值
Class<?> c = Class.forName(className);//通过得到的目标类的路径获取该类的字节码对象
Constructor<?> con = c.getConstructor();//通过反射获取该类的构造方法对象
Object obj = con.newInstance();//通过构造方法创建对象
Method method = c.getMethod(methodName);//通过放射得到该类的方法
method.invoke(obj);//通过反射调用方法
}
}