Annotation and reflection in JAVA

annotation

Annotations are divided into built-in annotations, meta annotations and user-defined annotations. Built-in annotations are often used, such as @ Override, @ SpringBootApplication, etc. when a java program is running, you can obtain annotation information through reflection, so as to process the annotated methods or classes accordingly. Meta annotations are annotations that define annotations and are used to declare the scope, time, etc. of annotations.
There are six yuan annotations. The first @ Documented: the annotation modified by @ Documented will be extracted into a document by JavaDoc, which is generally not understood. The second annotation @ Native: the annotation modified by @ Native annotation can be used to modify member variables, which can be referenced by local code. Generally, it is not necessary to understand them. The third annotation @ Repeatable: the annotation modified by @ Repeatable annotation can be reused and will not be used generally. The fourth annotation @ Target annotation: @ Target annotation can specify where modified annotations are used. It is specified by the elements in the ElementType enumeration class, such as @ Target({ElementType.ANNOTATION_TYPE,ElementType.FIELD}). ElementType has the following elements: constructor, field and local_ Variable (local variable), method (method), package (package), parameter (parameter), type (class or interface). The fifth annotation @ Retention: for the annotation modified by @ Retention, the action time of the modified annotation can be specified through the elements in RetentionPolicy, such as @ Retention(RetentionPolicy.CLASS). The RetentionPolicy enumeration class has the following elements: source (source file), class (in class file), and runtime (runtime). The sixth annotation @ Inherited: the annotation modified by the @ Inherited annotation can be automatically Inherited by subclasses.

@Annotation.MyAnnotation(name = "SuperQin")
public class Annotation {
    
    @Target({ElementType.TYPE,ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @interface MyAnnotation {
        //Annotation element: type + name ();
        String name() ;
        //Default annotation element default
        int age() default 0;
    }
    
}

reflex

Reflection is the soul of framework design. The so-called reflection, in short, is to obtain the structure of the runtime class when the code is running, so that different responses can be made according to the structure, such as the annotations mentioned above. However, please note that reflection should be used with caution, because the speed of reflection will be much lower than the running speed of normal programs. In the JVM, each class has and only has one object. Usually, the instantiated object from NEW will point to this unique object.

	static class MyReflection1{
        public MyReflection1(){
            System.out.println("Reflection 1");
        }
    }

    static class MyReflection2 extends MyReflection1{
        public MyReflection2(){
            System.out.println("Reflection 2");
        }
    }

    public static void main(String[] args) throws ClassNotFoundException {
        MyReflection1 myReflection1 = new MyReflection1();
        Class cl1 = myReflection1.getClass();
        Class cl2 = MyReflection1.class;
        Class cl3 = Class.forName("zgq.reflectionandannotation.Reflection.MyReflection1");
        Class cl4 = Integer.TYPE;
        Class cl5 =  cl3.getSuperclass();
    }

After you get the unique object of the class, you can get all the structures of the class through the object. And operate.

  //Get class name
        cl1.getName();
        //Gets the public property in the class
        cl1.getFields();
        //Get all properties in the class
        cl1.getDeclaredFields();
        //Get all the methods in this class
        cl1.getDeclaredMethods();
        //Get public methods in class and parent class
        cl1.getMethods();
        //Get constructor
        cl1.getConstructors();
        
		//Creating objects through constructors
        cl1.getConstructor().newInstance();
        //Creating objects from objects
        cl1.newInstance();
        //Calling methods through reflection
        cl1.getMethod("test1").invoke(cl1.newInstance());
        //Calling properties through reflection
        cl1.getField("a").set(cl1.newInstance(),"set a property");
        //The above operation properties and methods cannot operate private methods and properties. You need to turn off security detection and speed up reflection
        cl1.getField("a").setAccessible(true);
        cl1.getMethod("test1").setAccessible(true);

   		//Get method parameter generics
        cl1.getMethod("test1").getGenericParameterTypes();
        //Get method return value generic
        cl1.getMethod("tets1").getGenericReturnType();
        //Get method exception information generic
        cl1.getMethod("test").getGenericExceptionTypes();

Finally, you can get annotations through reflection. You can get the annotations on the corresponding methods, classes and properties

    public static void main(String[] args) throws NoSuchMethodException {
        Class cl1 = Reflection.class;
        Method method = cl1.getMethod("annotationTest");
        Annotation1 annotation1 = method.getAnnotation(Annotation1.class);
        System.out.println(annotation1.test());
    }

    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    @interface Annotation1{
        String test();
    }

    @Annotation1(test = "Reflection get annotation test")
    public void annotationTest(){
    }

Tags: Java

Posted on Wed, 24 Nov 2021 13:59:23 -0500 by grabber_grabbs