Introduction to Java Basic Note –annotation annotations and use of custom annotations

Source: Internet
Author: User
Tags deprecated

Java Basic Note –annotation annotations and using custom annotations This article was published by arthinking 5 years ago |Java Basics |  number of Reviews 7 | Be onlookers 25,969 views+ 1, the work principle of annotation: 2, @Override Note: 3, @Deprecated Note: 4, @SuppressWarnings Note: 5, custom annotations: 5.1, add variables: 5.2, add default value: 5.3, Multivariate use enumeration: 5.4, array variable: 6, set the scope of the annotation: 6.1, in the custom annotations use example: 7, the use of reflection read Runtime retention policy annotation Information Example: 8, the use of limited annotations: 9, add annotations in the Help document: 10, To use inheritance in annotations:
1, annotation work principle:

The annotations feature is provided in JDK5.0, which allows developers to define and use their own annotation types. This feature consists of a syntax that defines the annotation type and a syntax that describes an annotation declaration, an API for reading annotations, a class file that uses a callout decoration, and a annotation processing tool.

annotation does not directly affect the semantics of the code, but can be seen as a tool or class library for the program. This in turn has an impact on the running program semantics.

Annotation can be read from a source file, class file, or through a reflection mechanism at run time.

2, @Override notes:
Override

Represents a method declaration that intends to override another method declaration in a superclass. If the method uses this annotation type for annotations but does not override the superclass method, the compiler generates an error message.

@Override annotations indicate that subclasses are overriding the corresponding methods of the parent class.

Override is a marker annotation that identifies the annotation,annotation name itself that represents the information to be given to the tool program.

Here is an example of using @override annotations:

Class A {    private String ID;    A (String id) {        this.id = ID;    }    @Override    Public String toString () {        return ID;}}    
3, @Deprecated notes:
Deprecated

With @Deprecated Annotated program elements, programmers are discouraged from using such elements, usually because it is dangerous or there is a better choice. The compiler warns you when you are using an disapproved program element or if you are performing an override in an disapproved code.

@Deprecated annotations indicate that the method is not recommended for use.

Deprecated is a marker annotation.

Here is an example of using @deprecated annotations:

Class A {    private String ID;    A (String id) {        this.id = ID;    }    @Deprecated    New A ("A123"); A.execute ();}}    
4, @SuppressWarnings notes:
Suppresswarnings

Indicates that the specified compiler warning should be deselected in the annotation element (and in all program elements contained in the annotation element). Note that the set of warnings that are deselected in a given element is a superset of all warnings that are deselected in the containing element. For example, if you comment on a class to suppress a warning and comment on a method to suppress another warning, both warnings will be deselected in this method.

Depending on the style, the programmer should always use this comment on the innermost nested element, where the use is valid. If you want to suppress a warning in a particular method, you should comment on the method instead of commenting on its class.

@SuppressWarnings annotations indicate suppression warnings.

Here is an example of using @suppresswarnings annotations:

@SuppressWarnings ("unchecked")void Main (string[] args) {    new ArrayList ();    List.add ("abc");}  
5. Custom Annotations:

When you use @interface to customize annotations, the Java.lang.annotation.Annotation interface is automatically inherited and other details are automatically completed by the compiler. When you define annotations, you cannot inherit other annotations or interfaces.

Customize the simplest annotations:

Public @interface Myannotation {}

To use a custom annotation:

Class AnnotationTest2 {    @MyAnnotation    void execute () {        System.out.println ("method");}}  
5.1. Add variables:
Public @Interface Myannotation {    String value1 ();}

To use a custom annotation:

Class AnnotationTest2 {    @MyAnnotation (value1= "abc")    Void execute () {        System.out.println (" Method "); }}

When a property named value is used in an annotation, the property value interface can be written directly without specifying the name of the property, except that the value of the unexpected variable names needs to be assigned using the Name=value method.

5.2. Add default values:
Public @Interface Myannotation {    "abc";} 
5.3. Multivariate Use enumeration:
Public @Interface Myannotation {    "abc";    default Myenum.sunny;} Enum myenum{    Sunny,rainy}  

To use a custom annotation:

Class AnnotationTest2 {    @MyAnnotation (value1= "a", Value2=myenum.sunny)    Void execute () {        System.out.println ("method");}}  
5.4. Array variables:
Public @Interface Myannotation {    "abc";} 

To use a custom annotation:

Class AnnotationTest2 {    @MyAnnotation (value1={"A", "B"})    void execute () {        System.out.println ( "method"); }}
6, set the scope of the annotation:
Retention

Indicates how long comments for the comment type are to be retained. If the Retention comment does not exist in the annotation type declaration, the retention policy defaults to Retentionpolicy.class.

The Target meta Comment is valid only if the meta-comment type is used directly for comments. Invalid if the meta-comment type is used as a member of another annotation type.

Retentionpolicyextends enum<retentionpolicy>

Note retention policies. Constants for this enumeration type describe the different policies that preserve annotations. They are used with the Retention meta annotation type to specify how long the comment is retained.

 The class compiler will record annotations in the class file, but the VM does not need to keep annotations at run time. The runtime compiler records annotations in the class file, and the VM retains comments at run time, so it can be read in a reflective manner. The comment that the SOURCE compiler will discard.

@Retention annotations can provide a retention policy for annotations to the compiler when defining annotations.

Annotations that belong to the class retention policy are @suppresswarnings, and the annotation information is not stored in the. class file.

6.1. Examples of use in custom annotations:
@Retention (retentionpolicy.class) public@interface Myannotation {    "abc";}  
7. Use reflection to read the annotation information of the runtime retention policy example:
Java.lang.reflect        annotatedelement All known implementation classes:        AccessibleObject, class, Constructor, Field, Method, Package

Represents a commented element for a program that is currently running in this VM. This interface allows the annotation to be read in a reflective manner. All annotations returned by methods in this interface are immutable and serializable. The caller can modify the array returned by the accessor of an assigned array enumeration member, which does not have any effect on the array returned by other callers.

If a method in this interface returns a comment (directly or indirectly) that contains a class member that has been assigned a value, which refers to one of the classes that is not accessible in this VM, then attempting to read the class by invoking the method returned by the related class on the returned comment will result in a Typenotpresentexception.

isannotationpresent (class< extends annotation> annotationclass)

Returns true if a comment of the specified type exists on this element, otherwise false is returned. This method is designed primarily for easy access to tag annotations.

Parameters:

Annotationclass-Class object corresponding to the annotation type

Return:

Returns true if a comment of the specified annotation type exists on this object, otherwise false

Thrown:

NullPointerException-If the given annotation class is null

Start from the following versions:

1.5

getannotation (class<t> Annotationclass)

If there is a comment of the specified type for the element, the comments are returned, otherwise null is returned.

Parameters:

Annotationclass-Class object corresponding to the annotation type

Return:

If the annotation of the specified annotation type for the element exists on this object, the comments are returned, otherwise null is returned

Thrown:

NullPointerException-If the given annotation class is null

Start from the following versions:

1.5

getannotations ()

Returns all comments that exist on this element. (If this element has no comments, a zero-length array is returned.) The caller of the method can arbitrarily modify the returned array, which does not have any effect on the array returned by other callers.

Return:

All annotations that exist on this element

Start from the following versions:

1.5

getdeclaredannotations ()

Returns all comments that exist directly on this element. Unlike other methods in this interface, the method ignores inherited annotations. (if no comment exists directly on this element, an array of zero length is returned.) The caller of the method can arbitrarily modify the returned array, which does not have any effect on the array returned by other callers.

Return:

All annotations that exist directly on this element

Start from the following versions:

1.5


The following is an example of annotation information that reads the runtime retention policy using reflection:

Custom annotations:

@Retention (retentionpolicy.runtime) public@interface Myannotation {    "abc";}  

To use a custom annotation:

Class AnnotationTest2 {    @MyAnnotation (value1={"A", "B"})    @Deprecated    void execute () { System.out.println ("method");}}   

Read the information in the annotations:

PublicStaticvoid Main (string[] args)Throws SecurityException, Nosuchmethodexception, IllegalArgumentException, Illegalaccessexception, invocationtargetexception {AnnotationTest2 AnnotationTest2 =New AnnotationTest2 ();Gets the Class instance of AnnotationTest2 class<annotationtest2> C = AnnotationTest2.ClassGets the methods that need to be handled method instance, method = C.getmethod ("Execute",new class[]{}); //Determine if the method contains myannotation annotation if (method.isannotationpresent (myannotation).  Class) { //Gets the myannotation annotation instance of the method myannotation myannotation = Method.getannotation (myannotation.  Class); //Execute the method Method.invoke (AnnotationTest2, new object[]{}); //Get myannotation string[] value1 = myannotation.value1 (); System.out.println (Value1[0]); } //Get all annotations on method annotation[] annotations = method.getannotations (); For (Annotation annotation:annotations) {System.out.println (Annotation);}}       
8, the use of limited annotations:

Qualifying annotations Use @target.

Target

Indicates the kind of program element that the annotation type applies to. If a Target meta comment does not exist in the annotation type declaration, the declared type can be used on either program element. If such a meta-comment exists, the compiler enforces the specified usage limit. For example, this meta-comment indicates that the declaration type is itself, the meta-comment type. It can only be used on annotation type declarations:

@Target (elementtype.annotation_type) public    @interface Metaannotationtype {        ...    } 

This meta-comment indicates that the claim type can only be used as a member type in a complex annotation type declaration. It cannot be used directly for annotations:

@Target ({}) public     @interface MemberType {        ...    } 

This is a compile-time error, which indicates that a ElementType constant appears more than once in the Target annotation. For example, the following meta-annotations are illegal:

@Target ({Elementtype.field, Elementtype.method, Elementtype.field}) public    @interface Bogus {        ...    }
ElementTypeextends enum<elementtype>

The program element type. Constants of this enumeration type provide a simple classification of elements declared in a Java program.

These constants are used with the Target meta comment type to specify under what circumstances it is legal to use the annotation type.

annotation_type Annotation type declaration CONSTRUCTOR Construction method Declaration Field Field declaration (including enumeration constants)local_variable Local variable declaration  method declares the  package Packet declaration PARAMETER parameter declaration type class, interface (including comment type) or enumeration declaration


Examples of usage limitations of annotations:

@Target (Elementtype.method) public@interface Myannotation {    "abc";}  
9. Add annotations to the Help documentation:

To add the annotation information to the API file while making the Javadoc file, you can use java.lang.annotation.Documented.

Declare the build annotations document in the custom annotations:

@Documented public@interface Myannotation {    "abc";}  

To use a custom annotation:

Class AnnotationTest2 {    @MyAnnotation (value1={"A", "B"})    void execute () {        System.out.println ( "method"); }}
10. Use Inheritance in annotations:

Annotations are not inherited into subclasses by default, and you can use inheritance with java.lang.annotation.Inherited annotation declarations when you customize annotations.

Inherited

Indicates that the annotation type is automatically inherited. If a inherited meta comment exists in the annotation type declaration, and the user queries the annotation type in a class of declaration, and there is no comment of that type in that declaration, the annotation type is automatically queried in the superclass of the class. This process repeats until a comment of this type is found or the top level (Object) of the class hierarchy is reached. If no superclass has a comment of that type, the query indicates that the current class does not have such a comment.

Note that if you use anything other than the comment type comment class, the meta-comment type is not valid. Also note that this meta-comment only facilitates the inheritance of comments from the superclass, and the annotations to the implemented interfaces are not valid.

In addition to the article has special instructions, are it house original articles, reproduced please link the form to indicate the source.
This article link: http://www.itzhai.com/ java-based-notebook-annotation-annotation-introduction-and-use-custom-annotations.html keywords: annotation, Java, annotationsarthinkingJava Technology Exchange Group: 280755654, starter Group: 428693174 More

Introduction to Java Basic Note –annotation annotations and use of custom 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.