Notes Full parsing of Java annotations

Source: Internet
Author: User

Java annotations

Annotations (Annotation), also called Meta data. A description of the code level. It is a feature introduced in JDK1.5 and later versions, with classes, interfaces, and enumerations at the same level. It can be declared in front of packages, classes, fields, methods, local variables, method parameters, and so on, to explain these elements, comments.

1. Classification of annotations 1.1 by operating mechanism
    1. SOURCE annotations
      Annotations exist only in the source code and are compiled into a. class file that does not exist.
    2. Compile-time annotations
      Annotations exist in both the source code and the. class file
      Like what:
    @Override    @Deprecated    @Suppvisewarnings
    1. Run-time annotations
      It also works in the run phase and even affects the annotations that run the logic.
1.2. Classification by source
    1. Annotations from the JDK
    2. Annotations from third parties
    3. Our own definition of annotations
2. customizing annotations 2.1. Syntax Requirements for custom annotations
    1. Defining annotations using the @interface keyword on a class
    2. Member declared without argument or exception
    3. You can specify a default value for a member with default
    4. Members are similar to restricted, valid types include primitive types and string,class,annotation,enumeration
    5. If the annotation has only one member, the member name must be named value (), and the member name and assignment number (=) can be ignored when used.
    6. Note Classes can have no members, annotations without members are called identity annotations
2.2. Annotations (meta-annotations)

Annotations are annotations, called meta-annotations

    1. retention annotations
      This type of annotation is retained at that stage,
      Retentionpolicy.source: Only in source code display, compile will discard
      Retentionpolicy.class: At compile time, it is recorded in CLASS, the runtime ignores
      Retentionpolicy.runtime: Runtime exists, can be read by reflection
    2. inherited annotations
      Allow subclasses to inherit,
      Identifies a normal class to inherit from a parent class, but the parent class can inherit annotations on the parent class when it is labeled by a custom annotation (with inherited annotations above the custom annotations)
    3. Documented annotations
      Include annotations when producing Javadoc (not included by default)
    4. Target annotations
      Identifies the scope of the annotation, for example: Elementtype.type can only be labeled on class classes
2.3. Using custom annotations
    1. Syntax for using annotations
      @ Note Name (member 1 = Member value 1, member 2 = member 2 value ...)
Next, write a custom annotation
Importjava.lang.annotation.Documented;ImportJava.lang.annotation.ElementType;Importjava.lang.annotation.Inherited;ImportJava.lang.annotation.Retention;ImportJava.lang.annotation.RetentionPolicy;ImportJava.lang.annotation.Target;/** * A simple custom annotation * /@Target({Elementtype.type,elementtype.field})//You can have this note identified on the class, and on the property@Retention(Retentionpolicy.runtime)//Indicates that the annotation can be obtained at run time@Inherited  //identifies a normal class to inherit a parent class, but when the parent class is annotated with the person annotation, the subclass can inherit the annotation type on the parent class@Documented //When producing Javadoc, include annotations Public@ interface Desc {String detail ();//Detailed description informationString value ()default "This man is very lazy and has nothing left.";}
Parsing annotations

To obtain runtime annotation information on a class, function, or member by reflection, thus realizing the logic of dynamic control program running

The following is an explanation of the annotations under the introduction of a small Li Zilai for obtaining commodity information.
1. Define a parent class, abstract the information of the product

/** * 商品信息父类  */@Desc(value="抽象类Goods类上的value值",detail="抽象类Goods类上的详细描述")publicabstractclass Goods {    @Desc(detail="抽象类Goods属性上的详细描述")    public"默认出生";  //商品的初始化信息介绍}
    1. Define a specific commodity class
/** 商品苹果 */publicclass Apple extends Goods{    publicint10//价格}
    1. Start the parsing demo get the information above the annotations
 Public  class Test {     Public Static void Main(string[] args)throwsIllegalArgumentException, illegalaccessexception {Apple Apple =NewApple (); class<? Extends apple> C = Apple.getclass ();//Gets the specified type annotation on the class        BooleanFlag = C.isannotationpresent (Desc.class);if(flag) {If there is a desc annotation above the class, @Inherited can be seen here, if there is no such annotation, it is not possible to get the desc annotation.Desc ClassType = c.getannotation (Desc.class); System.out.println (Classtype.value () +","+ Classtype.detail ()); }//Get the value above the propertyfield[] fields = C.getfields (); for(Field field:fields) {if(Field.isannotationpresent (Desc.class)) {Desc d = field.getannotation (Desc.class);//@Inherited more visible here, the annotation information on the parent class is completely inherited.System.out.println ("Properties:"+ field.getname () +"The message on the note is:"+ d.value () + d.detail ()); }        }    }}

Execution Result:
Abstract class goods value on class, abstract class goods description on class
Properties: The information on the annotations on Initinfo is: This man is lazy, nothing left. A detailed description of the abstract class goods attribute

3. Mixed small chestnuts

Simulates a simple hibernate example of generating SQL statements using entity objects
1. Writing annotations for the simulation table

/** 模拟表的信息 **/@Target({ ElementType.TYPE })@Retention(RetentionPolicy.RUNTIME)public @interface Table {    String value();}

2. Writing annotations for simulation field information

/** 模拟表字段信息 */@Target({ ElementType.FIELD })@Retention(RetentionPolicy.RUNTIME)public @interface Column {    String value();}

3. Writing an object for a conditional query

/** Conditional Query Object **/ Public  class Filter {     Public Static FinalString GT ="GT";//greater than >    //Load condition Map value    PrivateMAP&LT;KV, string> map =NewHASHMAP&LT;KV, string> ();/** Set Condition * @param key property name * @param value corresponding to @param the condition of type query, default = = =. */     Public void SetValue(string key, String value,string type) {Map.put (NewKV (Key,value), type); } PublicMAP&LT;KV, string>Getmap() {returnMap };} Class KV {PrivateString K;PrivateString v; Public KV(string k, String v) {Super(); This. K = k; This. v = v; } PublicStringGETK() {returnK } Public void SETK(String k) { This. K = k; } PublicStringGetv() {returnV } Public void Setv(String v) { This. v = v; }}

4. Write the entity class and use our own annotations to map the table information

@Table("Tab_apple") Public  class Apple {    @Column("Apple_name")PrivateString name;//Name    @Column("Apple_price")Private DoublePrice//Price     PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; } Public Double GetPrice() {returnPrice } Public void Setprice(DoublePrice) { This. Price = Price; }}

5. Test and write code that generates SQL

ImportJava.lang.reflect.Field;ImportJava.util.Map; Public  class Test {     Public Static void Main(string[] args)throwsNosuchfieldexception, SecurityException {Filter f =NewFilter (); F.setvalue ("Name","Apple",NULL); F.setvalue ("Price","5", filter.gt); String sql = query (f, apple.class);//query here for name= apples and more than 5 of the price of the product information statementSYSTEM.OUT.PRINTLN (SQL);//Print generated SQL statements}/** * Generate SQL statement * * @param F * Conditional Object * @param clzz * Entity table Type * @return * @throws SecurityException * @throws nosuchfieldexception */     Public StaticStringQuery(Filter F, class<?> clzz)throwsNosuchfieldexception, SecurityException {///1: Get the annotation information on the entity, sir. into a basic query statement        if(!clzz.isannotationpresent (Table.class)) {Throw NewRuntimeException ("Please pass in an entity class");        } Table Table = Clzz.getannotation (Table.class); String tableName = Table.value ();BooleanFlag =false;//Append SQL, Mark SQL statement after SQLStringBuffer SB =NewStringBuffer (); Sb.append ("SELECT * from"). append (TableName);//2: Get conditions for all conditionsMAP&LT;KV, string> map = F.getmap (); for(Map.entry<kv, String> ent:map.entrySet ())            {KV kv = Ent.getkey ();            String type = Ent.getvalue (); Field field = Clzz.getdeclaredfield (KV.GETK ());//Gets the Property object corresponding to the Condition property            if(!field.isannotationpresent (Column.class)) {//If this property does not contain a column annotation ID, throws an exception                Throw NewRuntimeException ("Incoming parameter is wrong");            } Column column = Field.getannotation (column.class); ;if(flag) {Sb.append ("and"). Append (Parse (Column.value (), Kv.getv (), type)); }Else{flag =true; Sb.append ("where"). Append (Parse (Column.value (), Kv.getv (), type)); }        }returnSb.tostring (); }/** * Parsing conditions SQL * * @param k * field names in database tables * @param v * Value * @param type * Condition type * @return  */     Public StaticStringParse(string k, string V, String type) {String sql ="";if(Type! =NULL) {if(Type.equals (FILTER.GT)) {sql = k +">"+ V; }        }Else{sql = k +" = "+ V; }returnsql }}

Execution Result:
SELECT * from tab_apple where apple_name = Apple and Apple_price > 5

Write to the last

This example is very primitive. I did not learn the reflection. Let's see.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

[Note]java annotation full parsing

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.