How to use annotation annotation object in Java programming _java

Source: Internet
Author: User
Tags deprecated documentation reflection

Annotations (also known as metadata) provide a formalized way for us to add information to our code so that we can use it very easily at a later time.
 
1. Basic syntax
Java SE5 built-in three standard annotations
@Override: Indicates that the current method definition overrides the method in the superclass. If you're not careful with spelling mistakes, Or the method signature does not have a method for covering the
cover, the compiler issues an error
@Deprecated: If the programmer uses an element that is annotated as its, the compiler emits a warning message
@SupperessWarnings: Turn off improper compiler warning information.
Java SE5 Built-in four-dimensional annotations
@Target: Indicates where the annotation can be used. Possible ElementType parameters include:
1) constructor: constructor Declaration
2 field: Field declaration ( Include enum instance)
3) local_variable: local variable Declaration
4 method: Methods Declaration
5) PACKAGE: Package Declaration
6) PARAMETER: parameter declaration
7) Type: Class, Interface ( Include the annotation type) or an enum declaration
@Retention: Indicates the level at which the note information needs to be saved. Optional retentionpolicy parameters include:
1 SOURCE: Annotations will be discarded by the compiler
2) CLASS: Annotations are available in the class file, but are discarded by the VM
3) RUNTIME:VM will also retain annotations at run time, so you can read the annotation information by reflection
@Documented: Include this annotation in Javadoc
@Inherited : Allow subclasses to inherit annotations in the parent class
Most of the time programmers define their own annotations and write their own processors to handle them.
USECASE.JAVA  &NBSP

 package com;  
Import Java.lang.annotation.ElementType;  
Import java.lang.annotation.Retention;  
Import Java.lang.annotation.RetentionPolicy;  
 
Import Java.lang.annotation.Target; @Target (Elementtype.method)//is used to define where your annotations will be applied, and this applies as a method//to define at which level the annotation is available, in the Source class file (class), or at runtime (runtime) @  
 Retention (retentionpolicy.runtime) public @interface usecase {public int id ();  
Public String description () default "no description";  
 
} passwordutils. java package com; public class Passwordutils {@UseCase (id=47,description= "Passwords must contain in least one numeric") Public Boolea  
 n ValidatePassword () {return true;  
 @UseCase (id=48) public string Encryptpassword (string password) {return password;  
 @UseCase (id=49,description= "Jong_cai") public void ShowName () {System.out.println ("Jong_cai"); }  
}  

 
2. Write note Processor
  If there is no tool for reading annotations, the annotations are no more useful than annotations. In the process of using annotations. A very important part of the
is to create and use the annotation processor. The Java SE5 expands the reflection mechanism API to help programmers construct such tools. At the same time, it also provides an external tool apt helps programmers to parse Java source code with annotations. Here is a very simple annotation processor that we will use to read the Passwordutils class, and use the reflection mechanism to find the @usecase tag. We've provided a set of IDs worth it, and then it lists the use cases found in passwordutils, and the missing use cases.

 Usecasetracker.java package com;  
Import Java.lang.reflect.Method;  
Import java.util.ArrayList;  
Import java.util.Collections;  
 
Import java.util.List; public class Usecasetracker {public static void trackusecases (List<integer> List, class<?> cl) {for (M  
  Ethod m:cl.getdeclaredmethods ()) {usecase US = m.getannotation (Usecase.class);  
  if (US!= null) {System.out.println ("Found use case:" + us.id () + "" + us.description ());  
  List.remove (New Integer (Us.id ()));  
 (int i:list) {System.out.println ("warning:missing use case-" + i);  
 } public static void Main (string[] args) {list<integer> List = new arraylist<integer> ();  
 Collections.addall (list, 47,48,49,50,51);  
 Trackusecases (list, passwordutils.class); }  
}  


This program uses two methods of Reflection: Getdeclaredmethods () and Getannotation (), all of which belong to the Annotatedelement interface (both Class,method and field are implemented). The Getannotation () method returns a callout object of the specified type, where it is usecase, and returns a null value if there is no annotation of that type on the annotated method. Then we pass the call ID () and description () method extracts the value of an element from the returned UseCase object. where the Encryptpassword () method does not specify the value of the description at the time of the annotation, the processor obtains the default value through the description () method when processing its corresponding annotation. Description.

Annotation in the Java world is spread out, have the time to write this simple annotations article, is the article about the introduction of annotation, I hope you can throw bricks, learn together ...
Don't talk nonsense, practice is the hard truth.

3. Examples
Let's talk about the concept of annotation first, and then how to design their own annotation.
First, in the JDK's own java.lang.annotation package, open the following source files:

Source file Target.java

@Documented 
@Retention (retentionpolicy.runtime)  
@Target (elementtype.annotation_type) public  
@ Interface Target {  
  elementtype[] value ();  

@Documented 
@Retention (retentionpolicy.runtime) 
@Target (elementtype.annotation_type) public 
@ Interface Target { 
  elementtype[] value (); 
} 


The @interface is a keyword, in the design of annotations must be defined as a type of @interface, and can not use class or interface keywords (will not think Sun a bit stingy, Just like interface so much).

Source file Retention.java

@Documented 
@Retention (retentionpolicy.runtime)  
@Target (elementtype.annotation_type) public  
@ Interface Retention {  
  retentionpolicy value ();  
} 

@Documented 
@Retention (retentionpolicy.runtime) 
@Target (elementtype.annotation_type) public 
@ Interface Retention { 
  retentionpolicy value (); 
} 


See here, everyone may be blurred, do not know what to say, don't worry, look down. In the above files are used Retentionpolicy,elementtype These two fields, you may guess that this is two Java files. Indeed, the source code for these two files is as follows:

Source file Retentionpolicy.java

public enum Retentionpolicy {  
 source,  
 CLASS,  
 RUNTIME  
} public 

enum Retentionpolicy { 
 source, 
 CLASS, 
 RUNTIME 
} 

This is an enum type with a total of three values, namely Source,class and RUNTIME.
Source represents the annotation type of information will only remain in the program source code, if the source code is compiled, the annotation data will disappear, and will not be kept in the compiled. class file.
Class means that the annotation type of information is retained in the source code of the program, and it is kept in the compiled. class file, and will not load the information into the virtual machine (JVM) when executed. . Note that when you do not set a annotation type of retention value, the system default is class.
The third, is runtime, means that in the source code, compiled a good. class file to retain the information, in the execution of this information will be loaded into the JVM.
To cite an example, such as @override inside the retention set to source, the compilation succeeds do not have this some check information; instead, the retention in the @Deprecated is set to runtime, Indicates whether or not the method is deprecated when it is executed, except to warn us at compile time which is deprecated.


Source file Elementtype.java

 public enum ElementType {TYPE, FIELD, method, PARAMETER, constructor, Local_varia BLE, annotation_type,package} public enum ElementType {TYPE, FIELD, method, PARAMETER, constructor, Local_variab LE, annotation_type,package} 

The ElementType in the

   @target is used to specify which elements the annotation type can be used on. Description: Type (types), FIELD (properties), Method (methods), PARAMETER ( Parameters), constructor (constructor), local_variable (local variable), Annotation_type,package (package), where type (type) refers to the can be used in Class,interface, Enum and annotation type.
   In addition, from the 1 source code can be seen, @Target themselves to declare themselves, can only be used on annotation_type.
   If a annotation type does not indicate which elements @target use, then it can be used on any element, where the element refers to the eight types above.
   give a few correct examples:
   @Target (elementtype.method)
   @Target (value= Elementtype.method)
   @Target (elementtype.method,elementtype.constructor)   
    A specific reference to Javadoc documentation
  
   source Files They all use @documented,@ The purpose of documented is to allow this type of annotation information to be displayed on the JAVAAPI documentation; If not added, the information generated by this type will not be found when using Javadoc to generate API documents.
   Another point, if you need to inherit the annotation data to the subclass, you will use the @inherited annotation type.  
   
The following design is one of the simplest examples of annotation, the example of which is a total of four files;  
Description.java

 package lighter.javaeye.com;  
Import java.lang.annotation.Documented;  
Import Java.lang.annotation.ElementType;  
Import java.lang.annotation.Retention;  
Import Java.lang.annotation.RetentionPolicy;  
 
Import Java.lang.annotation.Target; @Target (Elementtype.type) @Retention (retentionpolicy.runtime) @Documented public @interface Description {String  
Value (); 
 
} package lighter.javaeye.com; 
Import java.lang.annotation.Documented; 
Import Java.lang.annotation.ElementType; 
Import java.lang.annotation.Retention; 
Import Java.lang.annotation.RetentionPolicy; 
 
Import Java.lang.annotation.Target; @Target (Elementtype.type) @Retention (retentionpolicy.runtime) @Documented public @interface Description {String val 
UE (); } 


Description: All annotation will automatically inherit java.lang.annotation this interface, so you can no longer inherit other classes or interfaces.
The most important point is how to set the parameters of the annotation type:
First, only two access rights, public or default, can be decorated. For example, String value (), where the method is set to the Defaul default type.
Second, the parameter members can only use the basic type Byte,short,char,int,long,float,double,boolean eight kinds of basic data types and string,enum,class,annotations data types, And some of these types of arrays. For example, String value (), where the parameter member is string.
Third, if there is only one parameter member, it is best to set the parameter name to "value" followed by parentheses. Example: The above example has only one parameter member.

Name.java

Package lighter.javaeye.com;  
 
Import java.lang.annotation.Documented;  
Import Java.lang.annotation.ElementType;  
Import java.lang.annotation.Retention;  
Import Java.lang.annotation.RetentionPolicy;  
Import Java.lang.annotation.Target;  
 
Notice the difference between the @target and the @description, and the parameter members are different  
@Target (elementtype.method)  
@Retention (retentionpolicy.runtime  
@Documented public 
@interface Name {  
  String originate ();  
  String community ();  
} 

Package lighter.javaeye.com; 
 
Import java.lang.annotation.Documented; 
Import Java.lang.annotation.ElementType; 
Import java.lang.annotation.Retention; 
Import Java.lang.annotation.RetentionPolicy; 
Import Java.lang.annotation.Target; 
 
Notice the difference between the @target and @description, the parameter members are different 
@Target (elementtype.method) 
@Retention ( Retentionpolicy.runtime) 
@Documented public 
@interface Name { 
  String originate (); 
  String community (); 
} 


Javaeyer.java

Package lighter.javaeye.com;  
 
@Description ("Javaeye, the best software Development Communication Community") public  
class Javaeyer {  
  @Name (originate= "founder: Robbin", community=) Javaeye ") Public  
  String getName ()  
  {return  
    null;  
  }  
    
  @Name (originate= "founder: Jiangnan white Dress", community= "Springside") public  
  String getName2 ()  
  {return  
    "borrows two-bit IDs, Write This example, please forgive me! ";  
  }  
} 


Package lighter.javaeye.com; 
 
@Description ("Javaeye, the best software Development Communication Community") public 
class Javaeyer { 
  @Name (originate= "founder: Robbin", community=) Javaeye ") Public 
  String getName () 
  {return 
    null; 
  } 
   
  @Name (originate= "founder: Jiangnan white Dress", community= "Springside") public 
  String getName2 () 
  {return 
    "borrows two-bit IDs, Write This example, please forgive me! "; 
  } 
} 

Write a class that can be run to extract javaeyer information testannotation

Package lighter.javaeye.com;  
 Import Java.lang.reflect.Method;  
 Import Java.util.HashSet;  
 
 Import Java.util.Set; public class Testannotation {/** * Author lighter * Description: Usage of specific Guan Tian annotation API See Javadoc documentation/Public s  
    tatic void Main (string[] args) throws Exception {String class_name = "Lighter.javaeye.com.JavaEyer";  
    Class test = Class.forName (class_name);  
    Method[] method = Test.getmethods ();  
    Boolean flag = Test.isannotationpresent (Description.class);  
      if (flag) {Description des = (Description) test.getannotation (Description.class);  
      System.out.println ("Description:" +des.value ());  
    System.out.println ("-----------------");  
    ///To save all methods using the @name in the Javaeyer to set to set<method> set = new hashset<method> ();  
      for (int i=0;i<method.length;i++) {Boolean otherflag = Method[i].isannotationpresent (Name.class);  
    if (Otherflag) Set.add (Method[i]);  
 }   For (method M:set) {Name name = M.getannotation (Name.class);  
      System.out.println (Name.originate ());  
    SYSTEM.OUT.PRINTLN ("Created Community:" +name.community ()); 
 
 }} package lighter.javaeye.com; 
 Import Java.lang.reflect.Method; 
 Import Java.util.HashSet; 
 
 Import Java.util.Set; public class Testannotation {/** * Author lighter * Description: Usage of specific Guan Tian annotation API See Javadoc documentation/Public St 
    atic void Main (string[] args) throws Exception {String class_name = "Lighter.javaeye.com.JavaEyer"; 
    Class test = Class.forName (class_name); 
    Method[] method = Test.getmethods (); 
    Boolean flag = Test.isannotationpresent (Description.class); 
      if (flag) {Description des = (Description) test.getannotation (Description.class); 
      System.out.println ("Description:" +des.value ()); 
    System.out.println ("-----------------"); ///To save all the methods using the Javaeyer to @name in set to set<method> set = new Hashset<methoD> (); 
      for (int i=0;i<method.length;i++) {Boolean otherflag = Method[i].isannotationpresent (Name.class); 
    if (Otherflag) Set.add (Method[i]); 
      To (method M:set) {Name name = M.getannotation (Name.class); 
      System.out.println (Name.originate ()); 
    SYSTEM.OUT.PRINTLN ("Created Community:" +name.community ()); 

 } 
   } 
}

Run Result:

Description: Javaeye, the best software development communication Community 
founder: Robbin 
created by the community: Javaeye 
founder: Jiangnan White 
created community: Springside


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.