Annotation_Analyze annotations (example: replace the previous configuration file with annotations)

Use (analyze) annotations in the program: Get the attribute value
defined in the annotation 1. Get the object defined by the annotation (Class, Method, Field)
2. Get the specified annotation
* getAnnotation(Class)
//In fact, it is generated in memory A subclass implementation object of the annotation interface

	            public class ProImpl implements Pro{
		                public String className(){
		                    return "cn.itcast.annotation.Demo1";
		                }
		                public String methodName(){
		                    return "show";
		                }
	            }
  1. Example of calling the abstract method in the annotation to obtain the configured property value
    :
/**
 * 描述需要执行的类名和方法名
 */
@Target({
    
    ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Pro {
    
    
    String className();
    String methodName();
}

public class Demo1 {
    
    
   public void show(){
    
    
       System.out.println("demo1...show");
   }
}

public class Demo2 {
    
    
   public void show(){
    
    
       System.out.println("demo2...show");
   }
}

/**
 * 框架类
 */

@Pro(className = "annotation.Demo1",methodName = "show")
public class ReflectTest {
    
    
    public static void main(String[] args) throws Exception {
    
    
        //可以创建任意类的对象,可以执行任意方法

        /*
            前提:不能改变该类的任何代码,可以创建任意类的对象,可以执行任意方法
         */

        //1.解析注解
        //1.1获取该类的字节码文件对象
        Class<ReflectTest> reflectTestClass = ReflectTest.class;
        //2.获取上边的注解对象
        //其实就是在内存中去生成了一个该注解接口的子类实现对象

        /*
            public class ProImpl implements Pro{
                public String className(){
                    return "annotation.Demo1";
                }
                public String className(){
                    return "annotation.Demo1";
                }
            }

         */
        Pro an = reflectTestClass.getAnnotation(Pro.class);
        //3.调用注释对象中定义的抽象方法,获取返回值
        String className = an.className();
        String methodName = an.methodName();
        System.out.println(className);
        System.out.println(methodName);

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

    }
}

Program demonstration:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44664432/article/details/109246451