JAVA筆記——自訂註解

來源:互聯網
上載者:User

標籤:java

  • 如何自訂註解
    • Target
    • Retention
    • Inherited
    • Documented
  • 如何使用自訂註解
    • 需求
    • 實現
    • 運行結果

如何自訂註解

這裡是一個自訂的註解

@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Inherited@Documentedpublic @interface AnnoDemo {    public int value1();    public String value2();    public String value3() default "value3";}

註解參數支援的資料類型:

  1. 所有基礎資料型別 (Elementary Data Type)(int,float,boolean,byte,double,char,long,short)
  2. String類型
  3. Class類型
  4. enum類型
  5. Annotation類型
  6. 以上所有類型的數組

如果只有一個屬性,那麼必須命名為value,如 public String value();

這裡出現了四個註解:

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

表示註解的範圍,它有以下幾種值

  1. ElementType.TYPE : 類或者介面

  2. ElementType.FIELD : 類的屬性

  3. ElementType.METHOD: 方法

  4. ElementType.PARAMETER : 參數

  5. ElementType.CONSTRUCTOR :建構函式

  6. ElementType.LOCAL_VARIABLE :局部變數

  7. ElementType.ANNOTATION_TYPE :註解

  8. ElementType.PACKAGE :包

Retention

表示註解的生命週期

  1. RetentionPolicy.SOURCE:註解將被編譯器丟棄

  2. RetentionPolicy.CLASS:註解在class檔案中可用,但會被VM丟棄

  3. RetentionPolicy.RUNTIME:將在運行期也保留注釋,因此可以通過反射機制讀取註解的資訊

Inherited

表示該註解可以被子類繼承

Documented

表示該註解會被產生javadoc文檔

如何使用自訂註解

這裡寫個簡單的例子

需求
  1. 編寫一個實體類User
  2. 編寫一個註解為Table,表示User對應的資料庫表
  3. 編寫一個註解為Column,表示User中屬性對應的表欄位
  4. 通過user執行個體自動產生查詢sql語句(條件查詢)
實現

Table註解

package com.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註解

package com.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實體類,使用Table和Column註解

package com.anno.test;@Table("USER")public class User {    @Column("ID")    private Integer id;    @Column("NAME")    private String name;    @Column("EMAIL")    private String email;    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getEmail() {        return email;    }    public void setEmail(String email) {        this.email = email;    }}

通過註解產生sql語句

package com.anno.test;import java.lang.reflect.Field;import java.lang.reflect.Method;public class TestMain {    public static void main(String[] args) {        User user1 = new User();        user1.setId(1);        User user2 = new User();        user2.setId(2);        user2.setName("peter");        User user3 = new User();        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);    }    /**     * 自動產生條件查詢sql     * @param object     * @return     */    public static String createSql(Object object){        StringBuffer sb = new StringBuffer();        Class c = object.getClass();        //判斷該類是否有Table註解        boolean tExist = c.isAnnotationPresent(Table.class);        if(!tExist){            return null;        }        //擷取Table註解        Table table = (Table) c.getAnnotation(Table.class);        //擷取註解的value(資料庫中對應的表明)        String tableName = table.value();        sb.append("SELECT * FROM ").append(tableName).append(" WHERE 1=1");        //擷取這個類的所有欄位        Field[] fields = c.getDeclaredFields();        for(Field field: fields){            //判斷該屬性是否有Column註解            boolean fExist = field.isAnnotationPresent(Column.class);            if(!fExist){                continue;            }            //擷取該欄位的註解            Column column = (Column)field.getAnnotation(Column.class);            //擷取註解的value(資料庫中對應的欄位名)            String columnName = column.value();            //通過get方法拿到該欄位的值            String fieldName = field.getName();            //get方法 = get + 欄位名(首字母大寫)            String getMethodName = "get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);            try {                //執行get方法                Method m = c.getMethod(getMethodName);                Object fieldValue =  m.invoke(object);                //拼接sql語句                if(fieldValue == null){                    continue;                }                if(fieldValue instanceof Integer){                    sb.append(" AND ").append(columnName).append("=").append(fieldValue);                }else if(fieldValue instanceof String){                    sb.append(" AND ").append(columnName).append("=‘").append(fieldValue).append("‘");                }            } catch (Exception e) {                e.printStackTrace();            }         }        return sb.toString();    }}
運行結果

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

JAVA筆記——自訂註解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.