Java notes: Annotations

Source: Internet
Author: User

First, the basic knowledge

Java supports embedding supplemental information in source files, which are called annotations (metadata). Annotations do not alter the behavior of the program, and therefore do not alter the semantics of the program.

Ii. statement

The above statement represents an annotation. Annotations can only contain method declarations and cannot provide implementations for these methods, but are implemented by Java. All annotation types automatically extend the annotation interface, which specifies the Annotationtype method that returns the object that invokes the annotation.

After the annotations are declared, they can be used for annotation declarations. All declarations can have annotations associated with them, and even annotations themselves can be annotated. When using annotations, you need to provide values for the members of the annotations.

class Solution {    @interface  myannotation {        String str ();         int default 0; // Use default values     }    = "Printhello", val = 1)      Public Static void print () {        System.out.println ("Hello");}    }
View Code


Iii. Specifying retention policies

The annotation retention policy determines where the annotations are discarded. Java defines three retention strategies in the Java.lang.annotation.RetentionPolicy enumeration:

    • The source policy only preserves annotations in the original file and discards the compilation period.
    • The class policy stores annotations in the class file at compile time, but the Java virtual machine cannot get these annotations.
    • The runtime policy provides permanent annotations.
Import java.lang.annotation.Retention; Import Java.lang.annotation.RetentionPolicy, @Retention (retentionpolicy.runtime) @ Interface myannotation {    String str ();     int Val ();}
View Code

Iv. using reflection to get annotations

If you specify a runtime retention policy for annotations, any program can use reflection to query for annotations at run time. The ability to obtain class-related information at run time when reflected.

Importjava.lang.annotation.Retention;ImportJava.lang.annotation.RetentionPolicy;ImportJava.lang.reflect.Method, @Retention (retentionpolicy.runtime) @Interfacemyannotation {String str (); intVal ();}classSolution {@MyAnnotation (str= "Annotation Content", val = 0)     Public Static voidprintannotation () {Solution OB=Newsolution (); Try{Class<?> C =Ob.getclass (); Method Method= C.getmethod ("Printannotation"); Myannotation Anno= Method.getannotation (myannotation.class);        System.out.println (anno); } Catch(Nosuchmethodexception exc) {System.out.println ("Method does not exist"); }    }     Public Static voidMain (string[] args) {printannotation (); }}
View Code

Get all annotations.

Importjava.lang.annotation.Annotation;Importjava.lang.annotation.Retention;ImportJava.lang.annotation.RetentionPolicy;ImportJava.lang.reflect.Method, @Retention (retentionpolicy.runtime) @InterfaceMyannotationa {String str ();} @Retention (retentionpolicy.runtime) @Interfacemyannotationb {intVal ();} @MyAnnotationA (str= "Class Annotation content") @MyAnnotationB (Val= 1)classSolution {@MyAnnotationA (str= "Method Annotation content") @MyAnnotationB (Val= 0)     Public Static voidprintannotation () {Solution OB=Newsolution (); Try{annotation[] annos=Ob.getclass (). Getannotations ();  for(Annotation A:annos) System.out.println (a); Method Method= Ob.getclass (). GetMethod ("Printannotation"); Annos=method.getannotations ();  for(Annotation A:annos) System.out.println (a); } Catch(Nosuchmethodexception exc) {System.out.println ("Method does not exist"); }    }     Public Static voidMain (string[] args) {printannotation (); }}
View Code


V. Related interfaces

Both the Getannotation method and the Getannotations method are defined by the Annotatedelement interface, which supports annotation reflection. Annotatedelement interface also defines the following methods:

    • The Getdeclaredannotations method returns all non-inherited annotations that exist in the calling object.
    • The Isannotationpresent method returns whether the annotation is associated with the object.

Vi. marking annotations

tag annotations are special types of annotations, which do not contain members. The only purpose of the markup annotation is to mark the Declaration, and the best way to determine if the markup annotation exists is to use the Isannotationpresent method.

Importjava.lang.annotation.Retention;ImportJava.lang.annotation.RetentionPolicy;ImportJava.lang.reflect.Method, @Retention (retentionpolicy.runtime) @InterfaceMarker {}classSolution {@Marker Public Static voidprintannotation () {Solution OB=Newsolution (); Try{Class<?> C =Ob.getclass (); Method Method= C.getmethod ("Printannotation"); System.out.println (Method.isannotationpresent (Marker.class)); } Catch(Nosuchmethodexception exc) {System.out.println ("Method does not exist"); }    }     Public Static voidMain (string[] args) {printannotation (); }}
View Code


Vii. Single-member annotations

Single-member annotations typically contain only one member, allowing for the use of abbreviated forms to specify member values. The member name must be value and must have a default value if other members are included.

Import java.lang.annotation.Retention; Import Java.lang.annotation.RetentionPolicy, @Retention (retentionpolicy.runtime) @ Interface Single {    String value ();     int default 0;} class Solution {    @Single ("Printhello")    publicstaticvoid  Print () {        System.out.println ("Hello");}    }
View Code

Eight, built-in annotations

    • retention specifies a retention policy and can only annotate other annotations.
    • Documented is a markup interface that notifies other tools that annotations will be documented and can only annotate other annotations.
    • Target specifies the type of claim that can be applied to annotations, and can only annotate other annotations. Multiple values can be specified at the same time.
    • Inherited is a markup annotation that indicates that a super-class annotation can be inherited by a quilt class and can only annotate other annotations.
    • Override is a markup annotation that indicates that the method in the superclass must be overridden and only the method can be annotated.
    • Deprecated is a markup annotation that indicates that the declaration is obsolete and has been superseded by a new form.
    • Functionalinterface indicates that an interface is a functional interface. A functional interface contains only an abstract method that is used by a lambda expression.
    • Safevarargs is a markup annotation that indicates that unsafe actions related to variable length parameters are not occurring and can only be used for methods and constructors.
    • Suppresswarnings indicates a warning that the compiler might report, using a string to represent the warning name.

Ix. Types of annotations

The earliest annotations can only be applied to declarations, but they can now be applied to most places where the type is used. Such annotations are called type annotations after they are expanded. Type annotations allow the tool to perform additional checks on the code to help avoid errors.

ImportJava.lang.annotation.ElementType;ImportJava.lang.annotation.Target, @Target (elementtype.constructor) @InterfaceConstructoranno {} @Target (Elementtype.type_use) @InterfaceTypeanno {} @Target (Elementtype.type_parameter) @InterfaceParameteranno {} @Target (Elementtype.field) @InterfaceFieldanno {}classsolution< @ParameterAnno t>{@FieldAnno @TypeAnnoPrivateT data; @ConstructorAnno solution (@TypeAnno T data) { This. data =data; }}
View Code

Java notes: Annotations

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.