Home > Java > javaTutorial > body text

Detailed explanation of Java Annotation features

黄舟
Release: 2017-03-30 10:51:46
Original
1236 people have browsed it

What is Annotation?

Annotation is translated into Chinese as annotation, which means to provide additional data information in addition to the logic of the program itself. Annotation has no direct impact on the annotated code. It cannot directly interact with the annotated code, but other components can use this information.

Annotation information can be compiled into a class file, or it can be retained in the Java virtual machine so that it can be obtained at runtime. Annotation can even be added to Annotation itself.

Those objects can be added with Annotation

Classes, methods, variables, parameters, and packages can be added Annotation.

Built-in Annotation

@Override OverloadingThe @Deprecated method or type annotated in the parent class is no longer recommended for use

@SuppressWarnings Prevent compile-time warning messages. It needs to receive an array of String as a parameter. The available parameters are:

  • unchecked

  • path

  • serial

  • finally

  • ##fallthrough

can be used with annotation on other annotations

@Retention

To determine the

lifecycle of the Annotation being saved, you need to receive an Enum object RetentionPolicy as a parameter.

public enum RetentionPolicy {
    /**
     * Annotations are to be discarded by the compiler.
     */
    SOURCE,

    /**
     * Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior.
     */
    CLASS,

    /**
     * Annotations are to be recorded in the class file by the compiler and
     * retained by the VM at run time, so they may be read reflectively.
     *
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME
}
Copy after login

@Documented Documented

@Target

Indicates the range that the Annotation can modify, and receives an Enum object EnumType array as parameter.

public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration */
    TYPE,

    /** Field declaration (includes enum constants) */
    FIELD,

    /** Method declaration */
    METHOD,

    /** Parameter declaration */
    PARAMETER,

    /** Constructor declaration */
    CONSTRUCTOR,

    /** Local variable declaration */
    LOCAL_VARIABLE,

    /** Annotation type declaration */
    ANNOTATION_TYPE,

    /** Package declaration */
    PACKAGE
}
Copy after login

@Inherited

This Annotation can affect subclasses of the annotated class.

Customized Annotation

We can customize Annotation after JSE5.0. Here is a simple example.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MethodAnnotation {

}
Copy after login

The following Person object uses a custom MethodAnnotation.

public class Person {

    public void eat() {
        System.out.println("eating");
    }

    @MethodAnnotation
    public void walk() {
        System.out.print("walking");
    }

}
Copy after login

We can obtain Annotation information through reflection.

 Class<Person> personClass = Person.class;
        Method[] methods = personClass.getMethods();
        for(Method method : methods){
            if (method.isAnnotationPresent(MethodAnnotation.class)){
                method.invoke(personClass.newInstance());
            }
        }
Copy after login

Output:

walking
Copy after login

We can also add methods to custom Annotation.

@Target(ElementType.TYPE)
public @interface personAnnotation {
    int id() default 1;
    String name() default "bowen";
}
Copy after login

The following is the use of personAnnotation.

@personAnnotation(id = 8, name = "john")
public class Person {

    public void eat() {
        System.out.println("eating");
    }

    @MethodAnnotation
    public void walk() {
        System.out.print("walking");
    }

}
Copy after login

How Annotation is processed

When the Java source code is compiled, a plug-in annotation processor of the compiler will process these annotations. The processor can generate report information or create additional Java source files or resources. If the annotation itself is added with the RententionPolicy runtime class, the Java compiler will store the metadata of the annotation in the class file. Then, the Java virtual machine or other programs can look up this metadata and process it accordingly.

Of course, in addition to the annotation processor that can handle annotation, we can also use reflection to handle annotation ourselves. Java SE 5 has an

interface called AnnotatedElement. Java's reflective object classes Class, Constructor, Field, Method and Package all implement this interface. This interface is used to represent the annotated program elements currently running in the Java virtual machine. Through this interface, you can use reflection to read annotations. The AnnotatedElement interface can access annotations marked with RUNTIME. The corresponding methods are getAnnotation, getAnnotations, and isAnnotationPresent. Because Annotation types are compiled and stored in binaries just like classes, the Annotations returned by these methods can be queried just like Querynormal Java objects.

Wide use of Annotation

Annotation is widely used in various

frameworks and libraries. Here are some typical applications.

Junit

Junit is a very famous

unit testing framework. When using Junit, you need to be exposed to a lot of annotations.

  • @Runwith custom test class Runner

  • @ContextConfiguration Set Spring’s ApplicationContext

  • @DirtiesContext Reload the ApplicationContext before executing the next test.

  • @Before Initialize before calling the test method

  • @After Process after calling the test method

  • @Test indicates that the method is a test method

  • @Ignore can be added to the test class or test method to ignore the operation.

  • @BeforeClass: Called before all test methods in the test class are executed, and only called once (the marked method must be

    static)

  • @AfterClass: Called after all test methods in the test class have been executed and only executed once (the marked method must be static)

Spring

Spring is known as configuration hell, and there are many Annotations.

  • @Service Add annotations to the service class

  • @Repository Add annotations to the DAO class

  • @Component Add annotations to component classes

  • @Autowired Let Spring automatically assemble beans

  • @Transactional Configure things

  • @Scope Configure the object survival scope

  • @Controller Add annotations to the controller class

  • @RequestMapping url path mapping

  • @PathVariable Maps method parameters to paths

  • @RequestParam Binds request parameters to method variables

  • @ModelAttribute is bound to the model

  • @SessionAttributes is set to the session attribute

Hibernate

  • @Entity Modifies the entity bean

  • @Table Maps the entity class to the table in the database

  • @Column Mapping column

  • @Id mapping id

  • @GeneratedValue This field is self-increasing

  • @Version version control or concurrency Control

  • @OrderBy Sorting Rules

  • @Lob Large Object Annotation

Hibernate and a lot more The annotations about the union and the annotations of inheriting are not meaningful to list here.

JSR 303 – Bean Validation

JSR 303 – Bean Validation is a data validation specification, and its verification of Java beans is mainly implemented through Java annotation.

  • @NullThe element annotated by must be null

  • @NotNull annotated The element must not be null

  • @AssertTrueThe annotated element must be true@AssertFalseThe annotated element must be false@Min(value)The annotated element must be a number whose The value must be greater than or equal to the specified minimum value

  • @Max(value)The annotated element must be a number, and its value must be less than or equal to the specified maximum value

  • @DecimalMin(value)The annotated element must be a number, and its value must be greater than or equal to the specified minimum value

  • @DecimalMax(value)The annotated element must be Is a number whose value must be less than or equal to the specified maximum value

  • @Size(max, min)The size of the annotated element must be within the specified range

  • @Digits (integer, fraction) The annotated element must be a number, and its value must be within the acceptable range

  • @Past The annotated element must be Is a past date

  • @FutureThe annotated element must be a future date

  • @Pattern(value)The annotated element Must conform to the specified regular expression

In fact, there are many frameworks or libraries that use annotation, so I won’t list them one by one here. I hope everyone can draw inferences. Learn more about annotations in Java.

The above is the detailed content of Detailed explanation of Java Annotation features. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template