- 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:
- All basic data Types (Int,float,boolean,byte,double,char,long,short)
- String type
- Class type
- Enum type
- Annotation type
- 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:
- Target
- Retention
- Inherited
- Documented
Target
Represents the scope of the annotation, which has the following values
-
Elementtype.type: Class or interface
-
Elementtype.field: Properties of a class
-
Elementtype.method: Method
-
Elementtype.parameter: Parameters
-
Elementtype.constructor: Constructors
-
Elementtype.local_variable: Local Variables
-
Elementtype.annotation_type: Annotations
-
Elementtype.package: Bag
Retention
Represents the life cycle of annotations
-
Retentionpolicy.source: Annotations will be discarded by the compiler
-
Retentionpolicy.class: Annotations are available in the CLASS file, but are discarded by the VM
-
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
- Write an entity class user
- Write a note as table that represents the database table for user
- Write an annotation as column that represents the table field for the attribute in user
- 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