使用注解来实现前面的博客文章(https://blog.csdn.net/weixin_42265250/article/details/99770810),前面使用的是采用配置配置文件来实现功能
1.编写自定义的注解:
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 MyAnno {
String className();
String methodName();
}
2.定义一个简单的实例类:
public class Person1 {
public void show(){
System.out.println("person1...show..");
}
}
3.编写主类运行类:
import java.lang.reflect.Method;
@MyAnno(className = "pri.xlf.resouce.Person1",methodName = "show")
public class MyMain {
public static void main(String[] args) throws Exception {
//获取字节码文件对象
Class<MyMain> cls = MyMain.class;
//获取MyMain上面的注解对象
//在内存中生成一个该注解接口的子类实现对象
MyAnno anno = cls.getAnnotation(MyAnno.class);
//通过 对象.方法名 进行获取值
String className = anno.className();
String methodName = anno.methodName();
//System.out.println("className:"+className+" methodName:"+methodName);
//获取指定名称的类的字节码文件
Class classname = Class.forName(className);
//获取该类的对象
Object obj = classname.newInstance();
//获取指定的方法对象
Method method = classname.getMethod(methodName);
//调用方法
method.invoke(obj);
}
}
4.运行结果:
5.总结:
之前使用 MyAnno anno = cls.getAnnotation(MyAnno.class);时获得的anno为null,是因为在编写注解的时候没有写上元注解@Retention(RetentionPolicy.RUNTIME)。