Java annotations

What are annotations

  • Java annotations, or annotations, are a new technology introduced in Java5

  • An Annotation does:

    • Not the program itself, but the interpretation of the program
    • Can be read by other programs (compilers, etc.)
  • Annotation format:

    • Unchecked Annotations exist in code with the @ annotation name. You can add numeric values such as SuppressWarnings(value=”unchecked”)
  • Annotation is used in, right?

    • It can be attached to package, class, Method, filed, etc., which is equivalent to adding additional auxiliary information to them. We can access these metadata through reflection mechanism programming

Yuan notes

  • Meta-annotations are responsible for annotating other annotations. Java defines four standard meta-annotation types that provide annotations for other annotation types
  • These types and the classes they support are found in the Java.lang. annotation package (@target, @Retention, @Documented, @Inherited)
    • @target: Used to describe the scope of use (where annotations are used)
    • @retetion: indicates the level at which the annotation information needs to be guaranteed, used to describe the annotation lifecycle (source
    • Document: In English it means Document. It provides the ability to include elements from annotations into Javadoc.
    • Inherited an annotation modifs a parent class. When a child class is not modified by another annotation, its child class inherits the annotations

Custom annotations

When using the @ interface custom annotations, automatic inherited Java. Lang. The annotation. The annotation interface

public class Test03 {
   Annotations can display assignments. If there is no default value, be sure to assign a value to the annotation
   @myannotation2 (name = "aj",schloos = {" mechonome "})
   public void test(a){}@MyAnnotation3("")
   public void test2(a){}}@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface Myannotation2{
   // Annotated parameter, parameter type + parameter name
   String name(a) default  "";

   int age(a) default  0;

   // If the default value is -1, it does not exist
   int id(a) default- 1;

   String[] schloos() ;
}


@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface  MyAnnotation3{

   String value(a);
}

Copy the code

That’s all there is to annotating code, but the key is how we read the annotations, and that’s where reflection comes in, so let’s focus on Java reflection. Okay

Java reflection

Reflection is the key to Java’s recognition as a dynamic language. Reflection allows programs to use the Reflection API to retrieve the internal information of any class during execution and to directly manipulate the internal knowledge and methods of any object

Class c = Class.forName("java.lang.String")
Copy the code

After the Class is loaded, the method area in the heap produces an object of type Class (each Class has only one Class object), which contains the complete structure information of the Class. We can see the structure of the class through this object. This object is like a mirror through which to see the structure of the class, so we call it reflection

Class Class

For each Class, the JRE reserves an immutable object of type Class, a Class object that contains information about a particular structure.

  • Class is itself a Class
  • Class objects can only be created by the system
  • A loaded CLass will only have one CLass instance in the JVM
  • A Class object corresponds to a.class file loaded into the JVM
  • Each instance of a Class remembers which Class instance it was generated from
  • Class provides a complete view of all loaded structures in a Class
  • The Class Class is the root of Reflection, and for any Class that you want to dynamically load and run, you have to get the corresponding Class object first

Common methods of the Class Class

! [image-20210502212459742](/Users/cb/Library/Application Support/typora-user-images/image-20210502212459742.png)

Reflection fetch object

public class Test02 {
    public static void main(String[] args) throws ClassNotFoundException {
        Person person = new Student();
        System.out.println("This man is."+person.name);

        // Get from the object
        Class c1 = person.getClass();
        System.out.println(c1.hashCode());

        // Get by forname
        Class c2 = Class.forName("reflection.Student");
        System.out.println(c2.hashCode());

        // By class name
        Class c3 = Student.class;
        System.out.println(c3.hashCode());

        // Get the parent typeClass c4 = c1.getSuperclass(); System.out.println(c4); }}@Data
class Person{
    public String name;
    public int age;
}


class Student extends  Person{
    public Student(a){
        this.name = "Students"; }}class Teacher extends  Person{
    public Teacher(a){
        this.name = "Teacher"; }}Copy the code

Reflection operation methods, properties

public class Test03 {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        Class c1 = Class.forName("reflection.Student");

        Student student = (Student) c1.newInstance();
        System.out.println(student.getName());

        // Operate the method by reflection
        Method setName = c1.getDeclaredMethod("setName", String.class);
        setName.invoke(student, "zhangshan");
        System.out.println(student.getName());


        Student student1 = (Student) c1.newInstance();
        Field name = c1.getDeclaredField("name");
        // Reflection cannot operate on private attributes directly, you need to manually turn off the program's security detection, setAccessible(true)
        name.setAccessible(true);
        name.set(student1,"lisi"); System.out.println(student1.getName()); }}Copy the code

Performance testing

public class Test04 {

    public static void test01(a){
        User user = new User();
        long startTime = System.currentTimeMillis();

        for (int i = 0; i <1000000000 ; i++) {
            user.getName();
        }
        long endTime = System.currentTimeMillis();

        System.out.println(endTime - startTime +"ms");
    }


    public static void test02(a) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        User user = new User();
        long startTime = System.currentTimeMillis();

        Class c1 = user.getClass();
        Method getName = c1.getDeclaredMethod("getName".null);

        for (int i = 0; i <1000000000 ; i++) {
            getName.invoke(user, null);
        }
        long endTime = System.currentTimeMillis();

        System.out.println(endTime - startTime +"ms");
    }


    public static void test03(a) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        User user = new User();
        long startTime = System.currentTimeMillis();

        Class c1 = user.getClass();
        Method getName = c1.getDeclaredMethod("getName".null);
        getName.setAccessible(true);

        for (int i = 0; i <1000000000 ; i++) {
            getName.invoke(user, null);
        }
        long endTime = System.currentTimeMillis();

        System.out.println(endTime - startTime +"ms");
    }

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { test01(); test02(); test03(); }}Copy the code

Reflection operation annotation

public class Test05 {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { Class<? > c1 = Class.forName("reflection.Customer");

        // Get annotations by reflection
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation:annotations){
            System.out.println(annotation);
        }

        // Get the value of the annotation
        TableAnnotation annotation = c1.getAnnotation(TableAnnotation.class);
        System.out.println(annotation.value());

        // Get the class specified annotation
        Field id = c1.getDeclaredField("id"); FiledAnnotation annotation1 = id.getAnnotation(FiledAnnotation.class); System.out.println(annotation1.columnName()); System.out.println(annotation1.length()); System.out.println(annotation1.type()); }}/ / class notes
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableAnnotation{
    String value(a);
}


@Data
@TableAnnotation("db_customer")
class Customer {

    @FiledAnnotation(columnName="id",type = "Long",length =10)
    private Long id;

    @FiledAnnotation(columnName="age",type = "int",length =10)
    private int age;

    @FiledAnnotation(columnName="name",type = "String",length =10)
    private String name;


}


// Method annotations
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FiledAnnotation{
    String columnName(a);

    String type(a);

    int length(a);
}

Copy the code