Introduction to Java Annotations (annotations)

Source: Internet
Author: User
Tags event listener

1. Introduction

Starting with JDK5.0, Java added support for metadata (MetaData), which is annotation. This is actually a special tag in the code that can be read during compilation, class loading, runtime, and handled accordingly.

By using annotation, the program developer can embed some supplemental information in the source file without changing the original logic. Code analysis tools, development tools, and deployment tools can be validated with these additional information

or to deploy.

annotation does not affect the execution of program code, regardless of the addition or deletion of annotation, the code is consistently executed. If you want to let the annotation in the program play a role in the run time, only through some kind of matching

Tools to access and process information in Annotation, access and process Annotation are collectively known as APT (Annotation processing tool).


2. Principle

http://rejoy.iteye.com/blog/1627355

http://blog.csdn.net/blueheart20/article/details/18810693

can refer to the JDK source code to see its implementation principle


3. Use

The basic annotation

@Override: Used only to specify the override method, which enforces that a subclass must overwrite the parent class's method.

@Deprecated: Indicates that a program element (class, method, and so on) is obsolete and the compiler will give a warning when other programs use an obsolete class or method. For example, tagging a method in a parent class is obsolete.

@SuppressWarnings ("Unchecked"): Represents the program element (and all child elements in the program element) that is marked by annotation to suppress the specified compiler warning.


Custom annotation

Use keyword @interface

Package com.java.anotion;


Public @interface Myannotation {

A annotation,default that defines two variables is the default value.

String name () default "Cheney";

int age () default 18;

}


Annotation are divided into two categories:

1, Mark annotation, no member definition, use their own existence to provide information for us.

2, metadata annotation, contains the member variables of the annotation, they can accept more metadata, so it becomes the meta-data annotation.


Extracting information from annotation

Java.lang.reflect new Interface Annotatedelement interface, the interface is implemented by the main reflection class, such as Class,constructor,field,method,package. The Reflection class enables you to obtain information such as annotations for the implementation class.


Two examples:

Example One

Package Com.java.anotion;import Java.lang.annotation.retention;import Java.lang.annotation.retentionpolicy;import Java.lang.annotation.target;import java.lang.annotation.elementtype;/** * Empty comment */@Retention (retentionpolicy.runtime ) @Target (elementtype.method) public @interface testable {}
package com.java.anotion;import java.lang.reflect.method;/** * @Testable Annotation Processing tool class   */ public class testprocessor {/** *  Reflection Clazz Call to add the name path, otherwise the packet can not find class exception  *  @param  clazz *  @throws  SecurityException *  @throws  classnotfoundexception */ Public static void process (String clazz)  throws SecurityException,  Classnotfoundexception{int passed = 0;int failed = 0;for (Method m :  class.forname (Clazz). GetMethods ()) {if (M.isannotationpresent (Testable.class)) {try {m.invoke (null); passed++;}  catch  (exception e)  {system.out.println ("Method"  + m +  "Run failed, exception:"  +  e.getcause ()); failed++;}}} System.out.println ("co-run"  +  (passed + failed)  +  "method, where successful"  + passed  +  "One, Failed"  + failed +  "a");}}
package com.java.anotion;/** *  annotation @testable target class  */ public class testableannotationtest {@Testablepublic  static void method1 () {} Public static void method2 () {} @Testablepublic  static void method3 () {throw  New runtimeexception ("Method3 runtimeexception");} Public static void method4 () {} @Testablepublic  static void method5 () {}public  static void method6 () {} @Testablepublic  static void method7 () {throw new  runtimeexception ("Method7 runtimeexception");} @Testablepublic  static void method8 () {}} 
Package Com.java.anotion;import java.util.arraylist;import java.util.list;/** * @author Youyang * * */public class Test ex Tends fruit{@MyAnnotation (name= "ch", age=6) public void foo () {System.out.println ("Еfoo");} @SuppressWarnings ("unchecked") public static void main (string[] args) throws Exception {//new Test (). Foo ();//list< string> list = new ArrayList (); Testprocessor.process ("Com.java.anotion.TestableAnnotationTest");}}

Example Two

Package Com.java.anotion;import Java.lang.annotation.retention;import Java.lang.annotation.retentionpolicy;import Java.lang.annotation.target;import java.lang.annotation.elementtype;/** * Note with member variable */@Retention ( Retentionpolicy.runtime) @Target (elementtype.field) public @interface actionlistenerfor {String listener ();}

package com.java.anotion;import java.awt.event.actionlistener;import java.lang.reflect.field; Import javax.swing.abstractbutton;public class actionlistenerinstaller {public static  void processannotations (object obj) {class cl = obj.getclass (); for (Field f  : cl.getdeclaredfields ()) {///speaking specifies that field is set to be freely accessible, avoid private inaccessible f.setaccessible (true);// Gets the comment actionlistenerfor a = f.getannotation (actionlistenerfor.class) of the actionlistenerfor type for the specified filed; if (a != null) {try {class listenerclass = class.forname (A.listener ()); actionlistener al =  (ActionListener)  listenerclass.newinstance (); abstractbutton ab =  (AbstractButton)  f.get (obj); Ab.addactionlistener (AL);}  catch  (classnotfoundexception e)  {e.printstacktrace ();}  catch  (instantiationexception e)  {e.printstacktrace ();}  catch  (Illegalaccessexception e)  {e.printstacktrace ();}}}} 
Package com.java.anotion;import java.awt.event.actionevent;import java.awt.event.actionlistener ; import javax.swing.jbutton;import javax.swing.jframe;import javax.swing.joptionpane;import  javax.swing.jpanel;public class annotationtest {private jframe jframe =  new jframe ("Bind event listener with annotations");//Com.java.anotion.annotationtest$oklistenter reflection is unsuccessful when referencing an inner class, Error @actionlistenerfor (listener= "Com.java.anotion.OkListenter") private jbutton ok = new  jbutton ("OK"), @ActionListenerFor (listener= "Com.java.anotion.CancelListenter") private jbutton  Cancel = new jbutton ("Cancel");p Ublic void init () {jpanel jp = new  JPanel (); Jp.add (OK); Jp.add (cancel); Jframe.add (JP); Actionlistenerinstaller.processannotations (this); Jframe.setdefaultcloseoperation (Jframe.exit_on_close); Jframe.setlocation (300, 200); jframe.setsize (500, 300); jframe.setvisible (true);} Public static void main (String[] args)  {new annotationtest (). Init (); /*class oklistenter implements actionlistener{public void actionperformed (ActionEvent  e)  {joptionpane.showmessagedialog (null,  "clicked the Confirm Button");}} Class cancellistenter implements actionlistener{public void actionperformed ( Actionevent e)  {joptionpane.showmessagedialog (null,  "Clicked the Cancel Button");}} */}
Package Com.java.anotion;import Java.awt.event.actionevent;import Java.awt.event.actionlistener;import Javax.swing.joptionpane;public class Cancellistenter implements Actionlistener{public void actionperformed ( ActionEvent e) {joptionpane.showmessagedialog (null, "clicked Cancel Button");}}
Package Com.java.anotion;import Java.awt.event.actionevent;import Java.awt.event.actionlistener;import Javax.swing.joptionpane;public class Oklistenter implements Actionlistener{public void actionperformed (ActionEvent e) {Joptionpane.showmessagedialog (NULL, "Click on the Confirm button");}}

JDK Meta-annotation

Four meta-annotation are provided under the Java.lang.annotation package.

@Retention: Used to specify how long the annotation can be retained. A value member variable that contains a retentionpolicy type.

Value has three values:

1. The Retentionpolicy.class compiler will record the annotations in the CLASS file. The JVM no longer retains annotations when running Java programs. This is the default value.

2. The Retentionpolicy.runtime compiler records the annotations in the class file. When you run a Java program, the JVM also retains the comment, which the program can get through reflection.

3. The Retentionpolicy.source compiler discards this policy comment directly.

Note: If the annotation type has only one value member variable, you can write the value directly without the Name=value form.


@Target: Used to specify which program elements the annotation modifies. Also contains a value member variable of type ElementType.

There are 8 value values:

Elementtype.annotation_type can only decorate ANNOTATION

Elementtype.constructor modifier Builder

Elementtype.field Modifying member variables

Elementtype.local_variable modifying local variables

Elementtype.method Modification Method definition

Elementtype.package Decoration Package Definition

Elementtype.parameter modifier Parameters

Elementtype.type a modified class, interface, or enumeration definition


@Documented: Used for the Bai Javadoc tool extracted into a document, if the note is in advance document description will have comments, otherwise not.


@Inherited: Specifies that the annotation being decorated by it will have inheritance. If the base class has @inherited, the class inheriting this base class also has this annotation.


4, improve

Using apt to handle annotation

The APT (annotation processing tool) is a processing annotation utility. It detects the source file and finds the annotation, using annotation for additional processing.

The annotation processor can generate additional source files and other files depending on the annotation in the source file (the content of the file is determined by the writer of the annotation processor) when processing annotation, and apt compiles

Generate the source code files and the original sources files, and generate them together with the class file.

The main purpose of the use of apt is to simplify the developer's workload, because apt can compile the source code of the program while generating some subordinate files (such as source files, class files, program release profiles, etc.), the contents of these ancillary files

are also related to the source code. In other words, the use of apt can replace the traditional maintenance of code information and ancillary files.


In order to be the system apt tool to read annotation in the source file, a annotation processor must be customized, and the writing processor requires the following four packages in the JDK lib directory Tools.jar:

COM.SUN.MIRROR.APT: Interfaces for interfacing with APT

Com.sun.mirror.declaration: An interface containing various encapsulated class Members, class methods, class declarations

Com.sun.mirror.type: Contains various interfaces that encapsulate the program elements in the source code.

Com.sun.mirror.util: Provides some tools for working with types and declarations.


For the use of apt, such as hibernate automatically generated bean properties file Xxx.xxx.xml, the implementation principle is apt. Write your own annotation,

Referencing a custom annotation in a bean class, the system calls apt to generate a configuration file for the response.



This article is from the "Cloud Beach" blog, please be sure to keep this source http://3950566.blog.51cto.com/3940566/1562371

Introduction to Java Annotations (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.