Design pattern basis

Java annotation

  • Java annotation annotation is actually a special mark in the code. It is used to replace the configuration file: the traditional way tells the class how to run through the configuration file. With annotation technology, developers can tell the class how to run through annotations. The typical application of annotation in Java technology is that you can get the annotation in the class through reflection technology to decide how to run the class.

  • Annotations can be marked on packages, classes, attributes, methods, method parameters and local variables, and multiple annotations can be marked at the same time.

Built in annotation:

  • @Override: checks whether the method is an overloaded method. If it is found that the method does not exist in its parent class or its referenced interface, a compilation error will be reported.
  • @Deprecated: marks an obsolete method. If this method is used, a compilation warning will be reported
  • @SuppressWarnings: instructs the compiler to ignore warnings declared in annotations

The following are annotations (meta annotations) that act on other annotations

  • @Retention: defines how long the Annotation is retained:
  1. Some annotations only appear in the source code and are discarded by the compiler;
  2. Others are compiled in the class file, and annotations are kept in the class file and discarded when loaded into the JVM virtual machine. This is the default behavior, so annotations without Retention annotations will adopt this strategy
  3. Others will be read when the class is loaded, and the annotations will be kept during the program running. At this time, all annotations defined on a class can be obtained through reflection

Function: indicates the level at which the annotation information needs to be saved, which is used to describe the annotation life cycle (i.e. to what extent the described annotation is valid)

The values (RetentionPoicy) are:

  1. SOURCE: valid in SOURCE file (i.e. SOURCE file retention)
  2. class: valid in class file (i.e. class reserved)
  3. RUNTIME: valid at RUNTIME (i.e. reserved at RUNTIME)
  • @Documented: the function of documented annotation is to describe whether to keep its annotation information when generating help documents for classes using javadoc tools.

  • @Target: describes the scope of use of annotations (i.e. where modified annotations can be used). The target annotation is used to describe the object range that can be modified by the annotation class it annotates: annotations can be used to modify packages, types (classes, interfaces, enumerations, annotation classes), class members (methods, construction methods, member variables, values), method parameters and local variables (such as loop variables and catch parameters), When defining annotation classes, @ target is used to know more clearly which objects it can be used to modify

  • @Inherited: make the annotation modified by @ inherited inherited inherited (if a class uses an annotation modified by @ inherited, its subclass will automatically have the annotation).

  • @Safevarargs: Java 7 began to support, ignoring any warnings generated by method or constructor calls that use parameters as generic variables.

  • @Functional interface: identifies an anonymous function or functional interface

  • @Repeatable: identifies that an annotation can be used multiple times on the same declaration.

Examples of simple meta annotations (modifying self written annotations):

@Documented
@Target(ElementType.METHOD)
@Retention(value = RetentionPolicy.RUNTIME)
public @interface MyAnnoation {
}

reflex

  1. The core of Java reflection mechanism is to dynamically load classes and obtain class details when the program is running, so as to operate the properties and methods of classes or objects. The essence is that after the JVM obtains the class object, it decompiles it through the class object to obtain various information of the object.

  2. Java is a language that compiles first and then runs. The type of object in the program is determined at the compilation time. When the program runs, it may need to dynamically load some classes. These classes are not loaded into the JVM because they were not used before. Through reflection, you can dynamically create objects and call their properties at run time without knowing who the running object is at compile time in advance.

Operated object People:

package zxc;

import zxv.Column;

public class People {
    @Column("user name")//Reflection annotation
    private String name;
    private int age;

    public People(){

    }
    public People(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

Reflected annotation:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
    String value();
}

Reflect:

//   Members in classes: methods, properties, constructors
    @Test
    public void reflect(){
        try {
            //Class [people] - > class (runtime class) -- > C [object]
            Class <?> c=Class.forName("zxc.People");//Load into memory


           //Get default constructor by reflection
            Constructor con=c.getConstructor();//Get default constructor
            People p=(People)con.newInstance();//Equivalent to instantiation
            p.setAge(12);
            System.out.println(p.getAge());
            //Non default constructor by reflection
            Constructor con1=c.getConstructor(String.class,int.class);//Get default constructor
            People p1=(People) con1.newInstance("like",12);
            System.out.println(p1.getName());


            //Method reflection
            Constructor con2=c.getConstructor();
            People p2=(People) con2.newInstance();
            Method m= c.getMethod("setName", String.class);//Reflection gets the setName method
            m.invoke(p2,"like");//p2.setName()
            Method m1= c.getMethod("getName");//Get getName method from reflection
            System.out.println(m1.invoke(p2));

            //Attribute reflection
            Constructor con3=c.getConstructor();
            People p3=(People) con3.newInstance();
            Field[] fs=c.getDeclaredFields();//Show all fields c.getFields() shows non private fields
            Arrays.asList(fs).forEach(f->System.out.println(f.getName()));
            //Reflection field
            Field f=c.getDeclaredField("name");//Because the property: name is private, this function does not have access to private properties
            f.setAccessible(true);//Give access
            f.set(p,"like");
            System.out.println(f.get(p));


          //Reflection array
            Object o =Array.newInstance(String.class,5);//  String []a=new String[5];
            Array.set(o,0,"awsl");
            Array.set(o,1,"yyds");
            Array.set(o,2,"hust");
            Array.set(o,3,"comq");
            System.out.println(Array.get(o,3));


            //Reflection annotation
            Class cq=People.class;//And Class c=Class.forName("zxc.People"); One meaning
            Field fsq[]=cq.getDeclaredFields();
            for(Field fq:fsq){
                if(fq.isAnnotationPresent(Column.class)){
                    Column cl=fq.getAnnotation(Column.class);
                    if(cl.value().equals("user name"));
                    System.out.println(cl);
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Tags: Java Spring RESTful

Posted on Tue, 28 Sep 2021 20:22:59 -0400 by adrianuk29