Java Annotation Detail + example

Source: Internet
Author: User
Tags deprecated reflection
Introduction to Annotations1.5 The introduction of annotations can be understood as a data that describes data, or as a method of describing metadata. Default annotations provided by Java: @Override, @Deprecated. Annotations are only meta data, and business logic-independent definition methods are in the Java.lang.annotation package Meta Annotations

Java provides 4-element annotations to define our annotations
1. @Target,
2. @Retention,
3. @Documented,
4. @Inherited 1. @Target,

@Target describes the range of objects that annotation modifies, which is used to describe the use of annotations
1. Constructor: Used to describe constructors
2. Field: Used to describe a domain
3. Local_variable: Used to describe local variables
4. Method: Used to describe methods
5. PACKAGE: Used to describe the package
6. PARAMETER: Used to describe parameters
7. Type: Used to describe classes, interfaces (including annotation types) or enum declarations
8. Annotation_type: Applicable to ANNOTATION type, declaring annotation type
9. type_parameter:1.8 version
type_use:1.8 version

Type_parameter and Type_use extend generic usage scenarios, including generics, superclass and interface implementations, and even the exception declarations of methods. 2. @Retention Source: Valid in the source file (that is, source file retention), discarded at compile time. Annotations do not have any meaning after compilation ends, so they are not written to byte code. For example: @Override
2.CLASS: Valid in class file (that is, class reservation). Discarded when the class is loaded. Useful in the processing of bytecode files. Annotations Use this method by default.
3.RUNTIME: Valid at run time (that is, run-time retention). is never discarded, and the runtime retains the annotation, so you can use the reflection mechanism to read the information ratio of the annotation. such as: @Deprecated. For example, the @autowired in Srping, @ResponseBody and so on belong to this kind.

Represents the level at which the annotation information needs to be saved to describe the life cycle of the annotation 3. @Inherited

Introduction :
A meta-annotation is a markup annotation @Inherited illustrates that a type being labeled is inherited. If a annotation type using the @inherited modifier is used for a class, the annotation will be used for subclasses of that class.

A custom annotation that is declared with this annotation, and when this custom annotation is used, the subclass automatically inherits the annotation if it is above the class, otherwise the subclass does not inherit the annotation. It is important to remember that annotations declared using inherited are only valid when used on a class, and are not valid for methods, attributes, and so on. 4. @Documented

A simple annotations markup annotation that indicates whether the annotation information is added to the Java document.

Indicates that this annotation should be logged by the Javadoc tool. By default, Javadoc does not include annotations.

Example:
Adding meta annotations with documented annotations on a method, the Javadoc command generates xxx.html files. You can see the annotation.
annotation Element

The elements defined in the annotation class are called annotation elements, and the following types are available for the annotation element:
-All basic data types (Int,float,boolean,byte,double,char,long,short)
-String type
-Class type
-Enum type
-Annotation Type
-All of the above types of arrays are actually used to notice problem 1. Assigning rules when using annotations without names,

If the annotation has only one attribute, then it is definitely assigned to the property.

If the annotation has more than one attribute, and if the attribute has a default value, you do not assign a value to the annotation name and assign the value to the attribute named "value".

If the annotation has more than one attribute, and there is a property that has no default value set, the error will be incorrect when you do not write the property name to assign the value. 2. If multiple annotation elements are defined in the annotation, unless the annotation element uses the default. Otherwise, you will need to assign values when you use this annotation. Example 1 annotations on a variable

1.1 Note Definition @Retention (retentionpolicy.runtime) @Target (elementtype.field) public @interface Fieldanno {public String F
    Ilename () Default "Defaultfilename";

public int value ();
    1.2 Use public class Myanno {@FieldAnno () private String mystr;    
...
} 1.3 Call/** * based on field name */public static void Getfieldanno () {try {field Myfiel = Myanno.
Class.getdeclaredfield ("MyStr");
            Myfiel.setaccessible (TRUE);
            Fieldanno Fieldanno = myfiel.getannotation (Fieldanno.class);
                if (Fieldanno!= null) {System.out.println ("----getfieldanno----");
                System.out.println (Fieldanno.filename ());
            System.out.println (Fieldanno.value ());
        } catch (Nosuchfieldexception e) {e.printstacktrace (); }/** * Search all fields */public static void GetFieldAnno2 () {field[] fields = MyAnno.class.ge
      Tdeclaredfields ();  for (Field field:fields) {if (Field.isannotationpresent (Fieldanno.class)) {Fieldanno fie
                Ldanno = Field.getannotation (Fieldanno.class);
                SYSTEM.OUT.PRINTLN ("----getFieldAnno2----");
                System.out.println (Fieldanno.filename ());
            System.out.println (Fieldanno.value ());
 }
        }


    }
2. Notes on General methods
2.1 Definition @Retention (retentionpolicy.runtime) @Target (elementtype.method) public @interface Methodanno {String Methodnam
Ett (); } 2.2 using @MethodAnno (Methodnamett = "Mycustomermethod") private static void MyMethod () {} 2.3 call/** * Based on method Name get/public static void Getmethodanno () {try {MyMethod = MyAnno.class.getDeclared
            Method ("MyMethod", MyAnno.class.getClasses ());

            Methodanno Methodanno = mymethod.getdeclaredannotation (Methodanno.class);
        System.out.println (Methodanno.methodnamett ());
        catch (Nosuchmethodexception e) {e.printstacktrace (); }/** * Query all methods */public static void GetMethodAnno2 () {method[] Mymethods = Myanno.class

        . GetMethods ();  For (method Method:mymethods) {if (Method.isannotationpresent (Methodanno.class)) {Methodanno
                Methodanno = Method.getdeclaredannotation (Methodanno.class); SysTem.out.println (Methodanno.methodnamett ()); }
        }

    }
3. Annotations on the construction method
3.1 Definition @Retention (retentionpolicy.runtime) @Target (elementtype.constructor) public @interface Constructoranno {bool
Ean IsDefault (); } 3.2 uses @ConstructorAnno (IsDefault = true) public Myanno () {} @ConstructorAnno (IsDefault = false) Publ
            IC Myanno (String name) {} 3.3 call/** * get/public static void Getconanno () {try {) based on the specified name
            Constructor defaultconstructor = MyAnno.class.getDeclaredConstructor ();
            Constructoranno constructoranno=defaultconstructor.getdeclaredannotation (Constructoranno.class);

            System.out.println (Constructoranno.isdefault ());
            Constructor constructor = MyAnno.class.getDeclaredConstructor (String.class);
            Constructoranno constructoranno2=constructor.getdeclaredannotation (Constructoranno.class);
        System.out.println (Constructoranno2.isdefault ());
        catch (Nosuchmethodexception e) {e.printstacktrace (); }/** * SearchAll construction methods of cable/public static void GetConsAnno2 () {constructor[] myconstructors = MyAnno.class.getConstructor

        S (); 
                For (constructor constructor:myconstructors) {if (Constructor.isannotationpresent (Constructoranno.class)) {
                Constructoranno Constructoranno = constructor.getdeclaredannotation (Constructoranno.class);
            System.out.println (Constructoranno.isdefault ()); }
        }
    }
4. Annotations on class
The 4.1 definition @Retention (retentionpolicy.runtime) @Target (elementtype.type)//Can modify class and Inteface public @interface Typeanno {
String type ();  4.2 Using the @TypeAnno (type= "Mytypeanno") public class Myanno {} 4.3 call/** * Query for the class's */public static void based on the class name
        Gettypeanno () {Typeanno Typeanno = MyAnno.class.getDeclaredAnnotation (Typeanno.class);
        System.out.println (MyAnno.class.isAnnotationPresent (Typeanno.class));

    System.out.println (Typeanno.type ()); /** * Query Package name all classes/public static void Getannotypeanno () {String basepackage = "Com.myannotati
        On "; try {//First find resource enumeration<url> enums = Thread.CurrentThread (). Getcontextclassloader (). getres
            Ources (Basepackage.replace (".", "/"));
                while (Enums.hasmoreelements ()) {URL URI = enums.nextelement (); if ("File". Equals (Uri.getprotocol ())) {//is the file of the file protocol String dirsstr = Uri.getfile ();//Get FilePath file Dirsfile = new file (dirsstr);//The Folder object to create file if (Dirsfile.isdirectory ()) { file[] files = dirsfile.listfiles ()//Get all files under this folder for (file file:files) {if (File.isfile ()) {String classname = basepackage + "." +
                                File.getname ();
classname = classname.substring (0, Classname.length ()-6);
                                System.out.println (classname);
                                Class clazz = class.forname (classname); if (Clazz.isannotationpresent (Typeanno.class)) {Typeanno Typeanno = (Typeanno) clazz.
                                    Getdeclaredannotation (Typeanno.class);
                                System.out.println (Typeanno.type ());
           }
                            }
                        }
                    }     A catch (IOException e) {e.printstacktrace ());
        catch (ClassNotFoundException e) {e.printstacktrace (); }
    }
5. Annotations of local variables
public void m (int a)  
@MyOwnAnnotation (some information)  
int b = 5;  
}

There is currently no way to get annotations on local variables by reflection (Https://stackoverflow.com/questions/17237813/elementtype-local-variable-annotation-type ) 6. Annotations on Parameters

6.1 definition @Retention (retentionpolicy.runtime) @Target (elementtype.parameter) public @  Interface Paramanno {string value ();} 6.2 uses public static void Memethod (@ParamAnno ("myvalue") String name1,string
    name2) {@LocalVariableAnno () String TT; } 6.3 Call public static void Getparamanno () {try {method method = MyAnno.class.getDeclaredMethod ("Me
            Method ", String.class, String.class);
            annotation[][] Paramss = Method.getparameterannotations ();
                    For (annotation[] parameterannotation:paramss) {for (Annotation annotation:parameterannotation) {
                        if (annotation instanceof paramanno) {Paramanno param = (paramanno) annotation;
                    System.out.println (Param.value ());
        catch (Nosuchmethodexception e) {e.printstacktrace ()}}}; }

    }
7. Package Annotation

Role
1, for labeling in the package on the annotation to provide convenience;
2. Declare the private class and constant of the package;
* 3, provide a package of the overall note 8. Annotation_type

To be continued 9. Type_parameter and Type_use

Java 8 Learning Notes (i) annotations used in spring aliasfor

Alias the annotation. Reference

Https://www.cnblogs.com/peida/archive/2013/04/24/3036689.html

Introduction to the retention, documented, inherited of Java annotations

About the use of meta-annotation inherited in Java annotations

Java Annotation Learning III: the use of Package-info.java

Spring4.2 new Features (i)

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.