Java notes--custom annotations

Source: Internet
Author: User

    • How to customize annotations
      • Target
      • Retention
      • Inherited
      • Documented
    • How to use custom annotations
      • Demand
      • Realize
      • Run results

How to customize annotations

Here is a custom annotation

@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Inherited@Documentedpublic @interface AnnoDemo {    publicintvalue1();    publicvalue2();    publicvalue3default "value3";}

Data types supported by annotation parameters:

    1. All basic data Types (Int,float,boolean,byte,double,char,long,short)
    2. String type
    3. Class type
    4. Enum type
    5. Annotation type
    6. Arrays of all types above

If there is only one property, then it must be named value, such as public String value ();

There are four annotations:

    1. Target
    2. Retention
    3. Inherited
    4. Documented
Target

Represents the scope of the annotation, which has the following values

    1. Elementtype.type: Class or interface

    2. Elementtype.field: Properties of a class

    3. Elementtype.method: Method

    4. Elementtype.parameter: Parameters

    5. Elementtype.constructor: Constructors

    6. Elementtype.local_variable: Local Variables

    7. Elementtype.annotation_type: Annotations

    8. Elementtype.package: Bag

Retention

Represents the life cycle of annotations

    1. Retentionpolicy.source: Annotations will be discarded by the compiler

    2. Retentionpolicy.class: Annotations are available in the CLASS file, but are discarded by the VM

    3. Retentionpolicy.runtime: Annotations are also preserved at run time, so the information of annotations can be read through the reflection mechanism

Inherited

Indicates that the annotation can be inherited by a quilt class

Documented

Indicates that the note will be generated Javadoc document

How to use custom annotations

Here's a simple example.

Demand
    1. Write an entity class user
    2. Write a note as table that represents the database table for user
    3. Write an annotation as column that represents the table field for the attribute in user
    4. Automatically generate query SQL statements from user instances (conditional query)
Realize

Table annotations

Packagecom. Anno. Test;Import Java. Lang. Annotation. Documented;Import Java. Lang. Annotation. ElementType;Import Java. Lang. Annotation. Inherited;Import Java. Lang. Annotation. Retention;Import Java. Lang. Annotation. Retentionpolicy;Import Java. Lang. Annotation. Target;@Target (ElementType. TYPE) @Retention (Retentionpolicy. RUNTIME) @Inherited @documentedpublic @interface Table {public String value ();}

Column annotations

Packagecom. Anno. Test;Import Java. Lang. Annotation. Documented;Import Java. Lang. Annotation. ElementType;Import Java. Lang. Annotation. Inherited;Import Java. Lang. Annotation. Retention;Import Java. Lang. Annotation. Retentionpolicy;Import Java. Lang. Annotation. Target;@Target (ElementType. FIELD) @Retention (Retentionpolicy. RUNTIME) @Inherited @documentedpublic @interface Column {public String value ();}

User entity class, using table and column annotations

 PackageCom.anno.test;@Table("USER") Public  class User {    @Column("ID")PrivateInteger ID;@Column("NAME")PrivateString name;@Column("EMAIL")PrivateString email; PublicIntegergetId() {returnId } Public void setId(Integer ID) { This. id = ID; } PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; } PublicStringGetemail() {returnEmail } Public void Setemail(String email) { This. email = email; }}

Generating SQL statements from annotations

 PackageCom.anno.test;ImportJava.lang.reflect.Field;ImportJava.lang.reflect.Method; Public  class testmain {     Public Static void Main(string[] args) {User User1 =NewUser (); User1.setid (1); User user2 =NewUser (); User2.setid (2); User2.setname ("Peter"); User User3 =NewUser (); User3.setid (3); User3.setname ("Tom"); User3.setemail ("[email protected]");        String SQL1 = Createsql (user1);        String sql2 = Createsql (user2);        String sql3 = Createsql (User3);        System.out.println (SQL1);        System.out.println (SQL2);    System.out.println (SQL3); }/** * Automatically generate conditional query SQL * @param Object * @return  */     Public StaticStringCreatesql(Object object) {StringBuffer SB =NewStringBuffer (); Class C = Object.getclass ();//Determine if the class has table annotations        BooleanTexist = C.isannotationpresent (Table.class);if(!texist) {return NULL; }//Get table annotationsTable table = (table) c.getannotation (Table.class);//Gets the value of the annotation (indicated in the database)String tableName = Table.value (); Sb.append ("SELECT * from"). Append (TableName). Append ("WHERE 1=1");//Get all fields of this classfield[] fields = C.getdeclaredfields (); for(Field field:fields) {//Determine if the attribute has column annotations            BooleanFexist = Field.isannotationpresent (Column.class);if(!fexist) {Continue; }//Get annotations for this fieldColumn column = (column) field.getannotation (Column.class);//Gets the value of the note (the corresponding field name in the database)String columnName = Column.value ();//Get the value of the field through the Get methodString fieldName = Field.getname ();//get method = Get + field name (first letter capitalized)String Getmethodname ="Get"+fieldname.substring (0,1). toUpperCase () +fieldname.substring (1);Try{//Execute Get methodMethod m = C.getmethod (Getmethodname); Object fieldvalue = M.invoke (object);//Splicing SQL statements                if(Fieldvalue = =NULL){Continue; }if(FieldvalueinstanceofInteger) {Sb.append ("and"). Append (ColumnName). Append ("="). append (Fieldvalue); }Else if(FieldvalueinstanceofString) {Sb.append ("and"). Append (ColumnName). Append ("= '"). Append (Fieldvalue). Append ("'"); }            }Catch(Exception e)            {E.printstacktrace (); }         }returnSb.tostring (); }}
Run results

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

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