Annotations in Java (Annotation)

Source: Internet
Author: User

Reprinted: 1190000007623013

Brief introduction

Annotations, Java provides a way for an element in the original program to correlate any information, the path of any element, and a method.

Annotations are labels that are inserted into the source code that can be processed using other tools. Annotations do not change the way programs are compiled. The Java compiler generates the same virtual machine directives for code that contains annotations and does not contain annotations. In Java, annotations are used as modifiers (such as public/static).

Annotations and annotations

Annotations are intended for human use, and annotations are for the program to invoke. One is that programmers write to another programmer, one that the programmer writes to the computer for parsing.

Common annotations
    • @Override: Modifying overloaded parent methods;

    • @Deprecated: Modifying the classes/methods/attributes that will be discarded in the future;

    • @SuppressWarnings: Turn off improper compiler warning messages.

Annotation Run mechanism classification
    • SOURCE annotations: Annotations only exist in the source code, compiled into a. class file does not exist;

    • Compile-time annotations: annotations exist in the source code and. class, the runtime does not exist;

    • Runtime annotations: exist at all stages and can affect program run logic.

Annotation Source Classification
    • Annotations from the JDK: such as @override/@Deprecated, etc.;

    • Three-party annotations: such as @test/@Before in JUnit, etc.;

    • Custom annotations: Annotations that are customized by meta annotations.

Meta annotations

Annotations are annotated for custom annotations.

  • @Target: Indicates the scope of the defined annotation, and its values include:

    • Elementtype.constructor: Construction method declaration;

    • Elementtype.field: attribute/field declaration;

    • Elementtype.local_variable: local variable declaration;

    • Elementtype.method: Method declaration;

    • Elementtype.package: Package declaration;

    • Elementtype.parameter: parameter declaration;

    • Elementtype.type: class interface declaration;

    • Elementtype.annotation_type: annotation type declaration;

    • Elementtype.type_parameter: type parameter declaration (@since 1.8);

    • Elementtype.type_use: Type use (@since 1.8)

  • @Retention: Customize the life cycle of annotations with values such as:

    • Retentionpolicy.source: Only in the source code display, compile-time discard;

    • Retentionpolicy.class: Compile-time logging to. CLASS, run-time ignored;

    • Retentionpolicy.runtime: Runtime exists and can be read by reflection.

  • @Inherited: A markup annotation that states that a labeled type is inherited and can inherit only from the class.

  • @Documented: A public API used to describe other types of annotation that should be labeled as program members, so it can be documented by tools such as Javadoc. Documented is a markup annotation with no members.

Custom annotations
@Target (Elementtype.method) @Target ({elementtype.method,elementtype.type}) @Retention (Retentionpolicy.runtime) @Inherited @documentedpublic @interface Description {    String desc () Default "";    String author () default "";    int age () default 18;}
    • Use keyword @interface to define annotations;

    • Member variables are declared in a non-parametric and non-unusual manner;

    • You can assign a default value to a member variable by using the default keyword;

    • The type of the member variable is restricted, including 原始类型、String、Class、Annotation、Enumeration ;

    • If the annotation has only one member variable, the member name must be named value (), and the member name and assignment number (=) can be ignored in use;

    • Annotations can have no members, and annotations with no members are called labeled Annotations.

Using annotations
@< annotation Name > (< member name 1>=< member value 1>,< member name 2>=< member Value 2> ...) @Description (desc = "I ' m class annotation") public class Annotationapp {    @Description (desc = "I m method Annotation", a Uthor = "Rudy") public    String Eyecolor () {        return ' red ';    }}
Parsing annotations

运行时it realizes the logic of dynamic control program running by getting the annotation information on the class, method and member through reflection.

Import Annotation.description;import Org.junit.test;public class Annotationtest {    @Test public    void Testparse () throws ClassNotFoundException {        //Remove Note        Class cls = Class.forName ("Annotation.annotationapp");        Boolean isexit =  cls.isannotationpresent (description.class);        if (isexit) {            //Do logic processing            Description annotation = (Description) cls.getannotation (description.class);            System.out.println ("Get annotation:" + annotation.desc ());        } else{            System.out.println ("no annotation!");}}    
    • Use the class loader to load classes and get class objects;

    • Determine if there are class annotations;

    • Take out class annotations and do logic processing;

    • Method annotations are similar.

Annotations in Java (Annotation)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.