Java Custom Annotations

Source: Internet
Author: User

Java annotations are some of the meta-information that is attached to the code, used by some tools to parse and use at compile and run time, to illustrate and configure functionality.
Annotations do not and do not affect the actual logic of the code, only the ancillary role. Included in the Java.lang.annotation package.

1, Yuan annotation

Meta annotations are annotations of annotations. including @Retention @Target @Document @Inherited four kinds.


1.1. @Retention: Define retention policies for annotations

@Retention (Retentionpolicy. SOURCE) //annotations only exist in the source code and are not included in the class bytecode file

@Retention (Retentionpolicy. Class) //default retention policy, annotations exist in the class bytecode file, but are not available at run time .

@Retention (Retentionpolicy.runtime) //annotations are present in the class bytecode file and can be obtained through reflection at run time

1.2. @Target: Define the purpose of the annotations

The source code is defined as:

@Documented @retention (retentionpolicy.runtime) @Target (elementtype.annotation_type) public @interface Target { Elementtype[] Value ();}

@Target (Elementtype.type) // interfaces, classes, enumerations, annotations

@Target (Elementtype.field) // fields, constants for enumerations

@Target (Elementtype.method) // method

@Target (Elementtype.parameter) // method Parameters

@Target (Elementtype.constructor) // constructor

@Target (elementtype.local_variable)// Local Variables

@Target (Elementtype.annotation_type)// annotations

@Target (elementtype.package)/ // pack

By the above source code can know, his elementtype can have multiple, an annotation can be class, method, field and so on

1.3. @Document: Note that the note will be included in the Javadoc

1.4, @Inherited: The description subclass can inherit this annotation from the parent class

2. Customization of Java annotations

Here is an example of a custom annotation

@Documented @target ({elementtype.type,elementtype.method}) @Retention (retentionpolicy.runtime) public @interface Yts {public enum Ytstype{util,entity,service,model} public ytstype ClassType () default Ytstype.util;}
@Documented @retention (retentionpolicy.runtime) @Target (elementtype.method) @Inheritedpublic @interface HelloWorld { Public String name () default "";}

@Retention (Retentionpolicy.runtime)

The annotation defined is that the annotations exist in the class bytecode file and can be obtained through reflection at run time.

@Target ({Elementtype.type,elementtype.method})

So this annotation can be a class annotation, or it can be an annotation of a method.

Such an annotation is customized, of course, the members of the annotation can be the basic data type, but also for the data, object, and so on

3 The annotations are defined, so how do we get them and parse the annotations?

The reflection mechanism of Java can help, get annotations, the code is as follows:

Public class parseannotation { public void parsemethod (Class clazz)   throws illegalargumentexception, illegalaccessexception, invocationtargetexception,  securityexception, nosuchmethodexception, instantiationexception{object obj =  Clazz.getconstructor (new class[]{}). newinstance (new object[]{}); for (method method :  Clazz.getdeclaredmethods ()) {     helloworld say = method.getannotation (helloworld.class);     string name =  "";      if (say != null) {      name = say.name ();       method.invoke (Obj, name);     }     yts yts =  (Yts) method.getannotation (Yts.class);     if (yts != null ) {     &NBsp;if (YtsType.util.equals (Yts.classtype ())) {     system.out.println ("This is  a util method ");    }else{        System.out.println ("This is a other method");         }     }    }    } @ Suppresswarnings ("Unchecked")  public void parsetype (Class clazz)  throws  Illegalargumentexception, illegalaccessexception, invocationtargetexception{  yts yts  =  (Yts)  clazz.getannotation (Yts.class);   if (Yts != null) {    if (YtsType.util.equals (Yts.classtype ())) {    system.out.println ("This is a  util class ");    }else{    system.out.println (" this is  A other class ");    }   } } } 

The previous method is to parse the method annotation, the latter method is to get the class annotation

The following is the test method class

@Yts (ClassType =ytstype.util) public class Sayhell {@HelloWorld (name = "Xiaoming") @Yts public void SayHello (String name) {if (name = = NULL | | name.equals (""))  {System.out.println ("Hello world!");  }else{System.out.println (name + "Say hello world!"); } }}
public static void Main (string[] args) throws IllegalArgumentException, Illegalaccessexception, InvocationTargetException, SecurityException, Nosuchmethodexception, instantiationexception {ParseAnnotation parse =  New Parseannotation ();  Parse.parsemethod (Sayhell.class); Parse.parsetype (Sayhell.class); }

Java 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.