题目
基于昨天的代码用注解的方式来替换掉配置文件
程序代码
注解类
package com.company.test;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 描述要执行的类名和方法名
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface pro {
public abstract String className();
public abstract String methodName();
}
测试类
package com.company.test;
import java.lang.reflect.Method;
@pro(className = "com.company.test.Person",methodName = "show")
public class MyTest {
public static void main(String[] args) throws Exception {
//解析注解,获取该类的字节码对象
Class<MyTest> clazz = MyTest.class;
//获取注解对象
//其实就是在内存中生成了一个该注解接口的子类实现对象
pro an = clazz.getAnnotation(pro.class);
//调用注解中定义的抽象方法,获取返回值
String className = an.className();
String methodName = an.methodName();
System.out.println(className+"===="+methodName);
//获取配置文件中定义的数据
//加载该类进内存
Class cls = Class.forName(className);
//创建对象
Object obj = cls.newInstance();
//获取方法对象
Method method = cls.getMethod(methodName);
//执行方法
method.invoke(obj);
}
}
运行结果
和昨天运行结果一致