Black Horse programmer _java Annotations

Source: Internet
Author: User
Tags deprecated

Introduction to Annotations (Annotation)Annotation (annotations) is a feature introduced in JDK5.0 and later versions. Annotations are a new type of Java (similar to interfaces), and are at the same level as classes, interfaces, enumerations, which are called as a type of java. It can be declared in front of packages, classes, fields, methods, local variables, method parameters, and so on, to explain these elements, comments. It has a lot of functions, such as compiling checks, generating documentation, code analysis, and so on. The role of annotationsAnnotations can be viewed as an interface, and an annotation instance is a dynamic proxy class that implements the interface. Annotations are mostly used to describe a class, method, field, or label. So that we can get an instance of that field or method's annotations by reflection during the run of the program, to decide what to do or what to do with it. several basic annotations provided by the JDKA. @SuppressWarnings the purpose of this annotation is to prevent the compiler from emitting certain warning messages. It can have the following parameters: Deprecation: Obsolete class or method warnings. Unchecked: An unchecked conversion warning was performed. Fallthrough: A warning when a switch block directly leads to the next situation without a break. Path: A warning when there is a nonexistent path in the classpath, source file path, and so on. Serial: A warning when a SERIALVERSIONUID definition is missing on a serializable class. Finally: a warning when any finally clause cannot be completed. All: A warning about all the above conditions. [email protected] The purpose of this annotation is to mark an obsolete class or method. C. @Override the annotation is used in front of the method to identify that the method is a method that overrides the parent class. Meta AnnotationsMeta annotations are annotations of annotations. including @Retention @Target @Document @Inherited four kinds. A. @Retention it is defined in front of an annotation class to illustrate the life cycle of the annotation. @Retention indicates at what level the annotation information is saved. Optional parameter value in enum type Retentionpolicy, it has the following parameters: @Retention (retentionpolicy.source)//annotations only exist in the source code, in the class bytecode file does not contain @Ret Ention (Retentionpolicy.class)//default retention policy, annotations will exist in the CLASS bytecode file, but not available at runtime, @Retention (Retentionpolicy.runtime)// Annotations are present in a class bytecode file and can be obtained through reflection at run time @Documented to include this annotation in Javadoc, which means that the annotation is extracted by the Javadoc tool into a document. The content in the Doc document differs depending on the content of the information for this annotation.        Quite with @see, @param and so on. @Inherited allow subclasses to inherit annotations from the parent classthinking: What are the attribute values for the three annotations, @Override, @SuppressWarnings, and @deprecated? the property value for @Override, @SuppressWarnings is source. the @Deprecated property value is runtime. B. @Target it is defined in front of an annotation class to illustrate which elements the annotation can be declared in, and the possible values in the enumeration class Elemenettype. It has the following parameters: @Target (elementtype.type)//interfaces, classes, enumerations, annotations @Target (Elementtype.field)//fields, enumerated constants @Target (Elementtype.method)//Parties Normal @Target (Elementtype.parameter)//method parameter @Target (elementtype.constructor)//constructor @Target (elementtype.local_variable )//local variable @Target (elementtype.annotation_type)//annotation @Target (elementtype.package)//package Packag annotations must be in Package-info.java Statement the life cycle of annotationsAn annotation can have three lifecycles, and its default life cycle is retained in a class file, but it can also be specified by a @retetion meta-annotation for its life cycle. A.java source file when a @retetion (retentionpolicy.source) annotation is defined before an annotation class, the note is kept in only one source file, and when the compiler compiles the source file into a class file, the It does not leave annotations defined in the source file in the class file. B. class file when a @retetion (retentionpolicy.class) annotation is defined in front of an annotation class, then the note remains in a class file, and when the class file is loaded into memory, the virtual opportunity removes the annotation. So that it cannot be accessed in the program. C. When a @retetion (retentionpolicy.runtime) annotation is defined in front of an annotation class during the run of the program, the annotations are present in memory during the run of the program. At this point, we can use reflection to get all the annotations defined on a class. Definition of AnnotationsA simple note: [email protected]{//define public final static properties ...//Set public abstract methods ...} A. Annotations can have member annotations and interfaces similar, it can only define final static properties and public abstract methods. B. Methods of annotations 1. Publicabstract2 is added by default before the method. When declaring a method, you can define the default return value of the method.       For example: Stringcolor () default "blue"; String[]color () default{"Blue", "Red",......} 3. The return value of a method can have 8 basic types of types, String, Class, enumeration, annotations, and arrays of these types. C. Use annotations (use with reference to the following annotations) Use of annotationsThe use of annotations is divided into three processes. Defining annotations--declaring annotations--getting annotations A. Defining annotations (referring to the annotation definitions above) B. Declaration Note 1. What elements are declared annotations if you do not specify a @target element annotation to limit its use when defining annotations, the annotation can Used before any one of the elements specified in the ElementType enumeration. Otherwise, it can only be declared before the element specified by the @target element annotation. General form: @ Annotation name () 2. Assigning the return value of the annotation method to each method that does not have a default return value defined in the annotation, the return value of each of its methods must be assigned when the annotation is declared. General form: @ Annotation Name (method name = method return value, ...) if the method returns an array, the method return value is written in the {} symbol @ Note Name (method name ={return value 1, return value 2, ...} ...) 3. For annotations that contain only the value method, the return value can be written only when the annotation is declared. C. Getting annotations The annotation instances on the element can be obtained by reflection for annotations during the lifetime of the operation. 1. Annotations declared in a class can be obtained by means of the getannotation or Getannotations method of the Class object. 2. Annotations declared in a field get 3 by using the Getannotation or Getannotations method of the Field object, declare annotations in one method Obtained by means of the getannotation or Getannotations methods of the Method object add advanced properties for annotationsThe property of the array type int [] arrayattr () default {-*-n}; @MyAnnotation (arrayattr={2,3,4}) If there is only one element in the array property, This time the attribute value section can omit the attribute of the large enumeration type Enumtest.trafficlamp lamp (); @MyAnnotation (Lamp=enumtest.trafficlamp.green) Attributes of the annotation type: metaannotation annotationattr () Default @MetaAnnotation ("xxxx"), @MyAnnotation ([email protected] ("yyy ) can be considered that the above @myannotation is an instance object of the Myannotaion class, the same thing, it can be considered that the above @MetaAnnotation is an instance object of the Metaannotation class, The calling code is as follows: metaannotation ma =  myannotation.annotationattr (); System.out.println (Ma.value ()); The detailed syntax for annotations can be understood by looking at the Java language Specification, which is the language specification of Java.   Example: Here is an example of annotation information that reads the RUNTIME retention policy using reflection:  custom annotations: @Retention (retentionpolicy.runtime) public @interface Myannotation {    string[] value1 () default "ABC";}    Use custom annotations: public class AnnotationTest2 {   @MyAnnotation (value1={"A", "B"})     @ deprecated    public void execute () {        SYSTEM.OUT.PRINTLN ("method");   }}& nbsp;  read information in annotations: public static void Main (string[] ARGS) throws SecurityException, Nosuchmethodexception,  illegalargumentexception, IllegalAccessException, InvocationTargetException {    AnnotationTest2 annotationTest2 = new AnnotationTest2 ();   // Get Class instances of AnnotationTest2     class<annotationtest2> c = annotationtest2.class;   // Get the method instance that needs to be processed     methods = C.getmethod ("Execute", New class[]{});   // Determine if the method contains myannotation annotations     if (method.isannotationpresent (myannotation.class)) {        Get the Myannotation annotation instance for this method         Myannotation myannotation = method.getannotation ( Myannotation.class);       //execute this method         Method.invoke (AnnotationTest2, new object[]{});       //Get myannotation        string[] value1 = myannotation.value1 ();        SYSTEM.OUT.PRINTLN (value1[0]);   }   //Get all annotations on the method &nbSp   annotation[] annotations = method.getannotations ();    for (Annotation annotation:annotations) {        System.out.println (annotation);   }}   Summary1. To use good annotations, you must familiarize yourself with the reflection mechanism of Java, as shown in the above example, the parsing of annotations is entirely dependent on reflection. 2. Do not abuse annotations. Usually we seldom touch and use annotations in the programming process, only design, and do not want to make the design too much configuration.

Black Horse programmer _java 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.