Java custom annotations and run-time by reflection get 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

Annotation class:

@Retention (retentionpolicy.runtime)//annotations exist in the class bytecode file and can be obtained through reflection at run time to @target ({Elementtype.field, Elementtype.method})//Define the action target of the annotation * * Scope field, enumeration's constant/method @documented//Description The annotation will be included in the Javadoc public @interface Fieldmeta {/** * is the serial number * @return */boolean ID () Default false;/** * Field name * @return */string name () default "";/** * Editable * @return */bool EAN editable () default true;/** * is displayed in the list * @return */boolean summary () default true;/** * Field Description * @return */string DESCRI Ption () Default "";/** * Sort field * @return */int order () default 0;}

entity class:

public class Anno {@FieldMeta (id=true,name= "serial number", order=1) private int ID, @FieldMeta (name= "name", order=3) Private String Name; @FieldMeta (name= "age", order=2) private int ages; @FieldMeta (description= "description", order=4) public String desc () {return " Java reflection gets annotation's test ";} public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;}}

Gets the help class for the annotation

Public class sortablefield {public sortablefield () {}public sortablefield (FieldMeta  meta, field field)  {super ();this.meta = meta;this.field = field; This.name=field.getname (); This.type=field.gettype ();} Public sortablefield (Fieldmeta meta, string name, class<?> type)  { Super (); this.meta = meta;this.name = name;this.type = type;} private fieldmeta meta;private field field;private string name;private  Class<?> type;public fieldmeta getmeta ()  {return meta;} Public void setmeta (Fieldmeta meta)  {this.meta = meta;} Public field getfield ()  {return field;} Public void setfield (Field field)  {this.field = field;} Public string getname ()  {return name;} Public void setname (String name)  {this.Name = name;} Public class<?> gettype ()  {return type;} Public void settype (Class<?> type)  {this.type = type;}}

To get annotations at run time, first create a base class:

Public class parent<t> {private class<t> entity;public parent ()  {init ();} @SuppressWarnings ("Unchecked") Public list<sortablefield> init () {list<sortablefield>  list = new ArrayList<SortableField> ();/**getclass (). Getgenericsuperclass () Returns a representation of this  Class  represents the Entity (class, interface, base type, or  void)  *   type of the direct superclass (the type in the class<t> generic), Then convert it to Parameterizedtype.  * getactualtypearguments () returns an array of  Type  objects that represent the actual type parameters of this type.  * [0] is the first one in this array.  *  in short, it is the actual type of the generic parameter that gets the superclass: */entity =  (class<t>) ((Parameterizedtype) This.getclass (). Getgenericsuperclass ()). Getactualtypearguments () [0];//fieldmeta filed = entity.getannotation (FieldMeta.class); if ( This.entity!=null) {/** Returns all fields in the class, including public, protected, default (package) access, and private fields, but does not include inherited fields  * entity.getfields (); Return only all accessible public fields of the class or interface represented by the object  *  the getdeclared** () method in class returns all Access fields, methods, etc.; *  can see api *  */fielD[] fields = entity.getdeclaredfields ();//for (field f : fields) {// Gets the annotation fieldmeta meta = f.getannotation (Fieldmeta.class) that contains fieldmeta in the field, if (meta!=null) { Sortablefield sf = new sortablefield (meta, f); List.add (SF);}} Returns all accessible public methods of the class or interface represented by the object Method[] methods = entity.getmethods (); for (Method m:methods) { Fieldmeta meta = m.getannotation (Fieldmeta.class); if (meta!=null) {sortablefield sf =  new sortablefield (Meta,m.getname (), M.getreturntype ()); List.add (SF);}} This method is the new Fieldsortcom class implementation comparator interface, to override the Compare method implementation sort//collections.sort (list, new fieldsortcom ()); Collections.sort (list, new comparator<sortablefield> ()  {@Overridepublic  int  Compare (SORTABLEFIELD&NBSP;S1,SORTABLEFIELD&NBSP;S2)  {return s1.getmeta (). Order ()-s2.getmeta (). Order ();//return s1.getname (). CompareTo (S2.getname ());//can also be compared with Compare}});} Return list;}}

To create a subclass inheritance base class:

public class child extends parent<anno>{}

Test class:

public class Testannotation {@SuppressWarnings ({"Unchecked", "rawtypes"}) public static void main (string[] args) {Parent c = new Child (); list<sortablefield> list = C.init ();//Get annotations inside classes in generics//Output results for (Sortablefield l:list) {System.out.println ("field name:" + L.getname () + "\ t field type:" +l.gettype () + "\ t annotation name:" +l.getmeta (). Name () + "\ t annotation Description:" +l.getmeta (). Description ());}}


Java custom annotations and run-time by reflection get 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.