# #自定义的注解有四个注意的内容:
* Target
@Target (Elementtype.type)//Where annotations can be used
* Retention
@Retention (Retentionpolicy.runtime)//life cycle
* Documented
@Documented
Other types of annotation should be used as public APIs for annotated program members, so they can be documented by tools such as Javadoc. Documented is a markup annotation with no members.
* Inherited
@Inherited//Can be inherited by quilt class
Example code:
Table.java
@Target (Elementtype.type)//The location @retention (retentionpolicy.runtime)//life cycle @documented//that annotations can use Other types of annotation should be used as public APIs for annotated program members, so they can be documented by tools such as Javadoc. Documented is a markup annotation with no members. @Inherited//can inherit public @interface Table {String value ();}
Column.java
@Target (Elementtype.field) @Retention (retentionpolicy.runtime) public @interface Column {String value ();}
Entity class
Person.java
@Table (' person ') public class Person {@Column ("id") private int ID, @Column ("name") private String name; @Column ("Age") private int age; @Column ("email") private String email; Get/set ...}
Test class
public static void Main (string[] args) {query (new person ());} public static String query (Object o) {Boolean b = O.getclass (). Isannotationpresent (Table.class); if (!b) {return null;} Table table = O.getclass (). Getannotation (Table.class); String tableName = Table.value (); System.out.println ("tablename>>" + tableName);//Get Table name field[] fields = O.getclass (). Getdeclaredfields (); for (Field F:fields) {Boolean feildisannotationed = F.isannotationpresent (Column.class), if (!feildisannotationed) { Continue;} Column C = f.getannotation (Column.class); System.out.println ("Value of column annotations:" + c.value ());//Gets the column name of the annotation string fieldName = F.getname (); SYSTEM.OUT.PRINTLN ("Column name:" + fieldName);//Gets the value of the column by reflection string GetMethod = "Get" + fieldname.substring (0, 1). toUpperCase () + Fieldname.substring (1); System.out.println ("Method Name:" + GetMethod); try {method = O.getclass (). GetMethod (GetMethod); System.out.println ("Return value of Method" "+ Method.invoke (o));} catch (Exception e) {e.printstacktrace ();}} return null;}
Java Custom Annotation