Recently in the third party to see the excellent open source library source, found a lot of places with annotations, here, feel necessary to make a summary of Java annotations, convenient for their own reference and we learn to understand.

This paper is mainly explained from the following three aspects:

  • Concepts, what Java annotations are;
  • What are the built-in annotations in Java?
  • Custom annotations, and parsing, how to use;

concept

Java provides a way and means of associating elements in the original program with any information and any metadata. Java1.5 introduced annotations, which are heavily used in many Java frameworks today, such as Hibernate, Jersey, and Spring. Annotations are embedded in the program as metadata. Annotations can be parsed by some parsing tool or compilation tool. We can also declare that annotations have an effect during compilation or execution.

Java native annotations

There are three standard annotations and four meta-annotations in Java. Here is a brief introduction:

Three standard notes:
  • Override means that a method overrides or overrides a parent class. When we want to override a method in a parent class, we need to use this annotation to tell the compiler that we want to override the method. This way the compiler prompts an error message when a method in the parent class is removed or changed.

  • @deprecated indicates that the method is obsolete. When a method or class is marked with the @deprecated annotation, it indicates that the method or class has expired and will no longer be Deprecated. If a programmer accidentally uses its elements, the compiler issues a warning message.)

  • @suppressWarnings means to ignore specified warnings, such as @suppViseWarnings (“Deprecation”)

These three comments should be familiar to everyone and are common in our everyday code, so I won’t go into them here.

Yuan comments:

Meta annotations, very important, the back of the custom annotations, will be used, so the back of a good understanding of:

  • @target is the scope of the annotation

    Indicates which attributes and methods in a class the annotation can be applied to. The value of the meta-annotation can be used if the scope type has more than one comma-separated typeTYPE.METHOD.CONSTRUCTOR.FIELDAnd so on. If the Target meta-annotation is not present, the defined annotation can be applied to any element of the program. The values are explained as follows:
    • @Target(ElementType.ANNOTATION_TYPE) :

      annotations
    • @Target(ElementType.CONSTRUCTOR):

      Constructor declaration
    • @Target(ElementType.FIELD):

      Field declarations
    • @Target(ElementType.LOCAL_VARIABLE):

      Local variable declaration
    • @Target(ElementType.METHOD):

      Method statement
    • @Target(ElementType.PACKAGE):

      Package declaration
    • @Target(ElementType.PARAMETER):

      Parameter declarations
    • @Target(ElementType.TYPE):

      Classes, interfaces (including annotations), enumerations
    • @Target(ElementType.TYPE_PARAMETER):

      type
    • @Target(ElementType.TYPE_USE):

      type

The three types elementType. TYPE_USE and elementtype. TYPE_PARAMETER are new to Java8.

  • @Retention

    Represents the life cycle of the annotation
    • @Retention(RetentionPolicy.CLASS)

      Annotations are stored in bytecode files by the compiler and discarded at run time, default retention behavior
    • @Retention(RetentionPolicy.RUNTIME)

      Saved by the VM and read by the reflection mechanism
    • @Retention(RetentionPolicy.SOURCE)

      Annotations remain in the source phase and are discarded by the compiler
  • @Inherited This annotation is an identifier meta-annotation, which indicates that the current annotation can be Inherited by a child annotation
  • Documented indicates that a Javadoc is generated with annotations

Custom annotations

Custom annotations are more common in framework design because they make programming simpler and code cleaner. Ha ha, there is another is to install the force, a look at the high, next to see how to customize annotations, and how to use custom annotations;

How do I customize annotations?
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Persion {
    String name();
    String sex();
    int age() default 20;
}
Copy the code

1. The above code is a complete custom annotation. Creating a custom annotation is similar to creating an interface, but the interface keyword of the annotation should start with the @ sign.

2.@Target represents the scope of this annotation. It applies to methods and classes. If there are more than one scope, it is surrounded by {}, and separated by,.

3.@Retention indicates the annotation life cycle. This example shows that the annotation life cycle is saved by the VIRTUAL machine and can be read by reflection mechanism

4. Members are declared with no parameters and no exceptions. You can use default to specify a default value for members. It is also important to note that if the annotation has only one member, the member name must be value(); You can omit the member name and assignment number (=);

5. Annotation classes can have no members. Annotations without members are called identity annotations.

How to use annotations
@Persion(name = "Xiaomi",sex = "man",age = 15)
public class Xiaomi {
    String fatherName;
}
Copy the code

Member 1 = member 1 value, member 2 = member 2 value,… Line;

Parsing the annotation
try { Class c=Class.forName("com.sz.annotationdemo.Xiaomi"); If (c==null){log. I ("ms","Persion class does not exist "); }else{ boolean isExist=c.isAnnotationPresent(Persion.class); if (isExist){ Persion persion= (Persion) c.getAnnotation(Persion.class); Log.i("ms",persion.name()+",,,"+persion.sex()+",,,"+persion.age()); }else {log. I ("ms","Persion annotation does not exist "); } } } catch (Exception e) { e.printStackTrace(); }Copy the code

Use reflection to obtain runtime annotation information on a class, function, or member to dynamically control the execution of a program. Use the forName() method to load the class and use getAnnotation(Persion. Class) to check if the class has an @persion annotation. Annotation inheritance only applies to classes, annotations on methods are not inherited, and all annotations in interfaces are not inherited. Run to end:

01-30 17:52:53. 638, 11283-11283 /? I/ms: Xiaomi,,,man,,,15Copy the code

You can use custom annotations, inject, and then get the injected data. Later, you can actually project to solve the annotation problem.

I do Android development for many years, later will be updated on android advanced UI,NDK development, performance optimization and other articles, more please pay attention to my wechat public number: thank you!


The Android thing. JPG