Java利用反射實現註解簡易功能

來源:互聯網
上載者:User

標籤:string類   測試   基礎資料型別 (Elementary Data Type)   ace   return   bool   ges   util   版本   

//自訂一個簡單的註解
@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.TYPE,ElementType.METHOD,ElementType.FIELD,ElementType.PARAMETER,ElementType.LOCAL_VARIABLE})
public @interface Dougest { String value() default "";}
import java.lang.reflect.Field;import java.util.HashMap;import java.util.Map;import java.lang.annotation.Annotation;//方法測試類別@Dougest("annotation Dougest at class ")public class TestAnnotation {    @Dougest("annotation Dougest at field")    String a = "2";    @Dougest    int b = 10000000;        public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {        TestAnnotation testAnnotation = new TestAnnotation();        testAnnotation.a = "123";        System.out.println(getObjectFieldsValue(testAnnotation));//結果 ==> {a=123, b=10000000}        System.out.println(getObjectFieldValueByFieldName(testAnnotation,"a"));//結果 ==> 123        System.out.println(getFieldValueByAnnotation(Dougest.class, testAnnotation));//結果 ==> {a=123, b=10000000}        Dougest d = (Dougest)TestAnnotation.class.getAnnotation(Dougest.class);//結果 ==>         System.out.println(d.value());//結果 ==> annotation Dougest at class     }        /**     * 擷取指定對象指定註解下屬性值     * @param annotation     * @param obj     * @return     * @throws IllegalArgumentException     * @throws IllegalAccessException     */    public static Object getFieldValueByAnnotation(Class<? extends Annotation> annotation,Object obj) throws IllegalArgumentException, IllegalAccessException{        if(obj == null)            throw new RuntimeException("cannot getFieldValueByAnnotation for null Object");        if(annotation == null)            throw new RuntimeException("cannot getFieldValueByAnnotation for null annotation");        Map<String,Object> map = new HashMap<String,Object>();        Field[] fields = obj.getClass().getDeclaredFields();        for(Field field : fields) {            field.setAccessible(true);            if(field.isAnnotationPresent(annotation)) {                map.put(field.getName(),field.get(obj));            }        }        return map;    }        /**     * 擷取對象屬性值     * @param obj     * @return     * @throws IllegalArgumentException     * @throws IllegalAccessException     */    @SuppressWarnings("rawtypes")    public static Map<String,Object> getObjectFieldsValue(Object obj) throws IllegalArgumentException, IllegalAccessException {        if(obj == null)            throw new RuntimeException("cannot getObjectFieldsValue for null Object");        Map<String,Object> map = new HashMap<String,Object>();        Class clazz = obj.getClass();        Field[] fields = clazz.getDeclaredFields();        for(Field field : fields) {            field.setAccessible(true);            map.put(field.getName(), field.get(obj));        }        return map;    }    /**     * 擷取對象屬性名稱擷取屬性值     * @param obj     * @return     * @throws IllegalArgumentException     * @throws IllegalAccessException     */    @SuppressWarnings("rawtypes")    public static Object getObjectFieldValueByFieldName(Object obj,String fieldName) throws IllegalArgumentException, IllegalAccessException {        if(obj == null)            throw new RuntimeException("cannot getObjectFieldValueByFieldName for null Object");        if(fieldName == null || "".equals(fieldName.trim()))            throw new RuntimeException("cannot getObjectFieldValueByFieldName for null fieldName");        Class clazz = obj.getClass();        Field[] fields = clazz.getDeclaredFields();        for(Field field : fields) {            field.setAccessible(true);            if(fieldName.equals(field.getName()))                 return field.get(obj);        }        return null;    }}

什麼是註解(what)

定義:

  註解(Annotation),也叫中繼資料。一種代碼層級的說明。它是JDK1.5及以後版本引入的一個特性,與類、介面、枚舉是在同一個層次。它可以聲明在包、類、欄位、方法、局部變數、方法參數等的前面,用來對這些元素進行說明,注釋。

我的理解:

   吾生而有涯,其學也無涯,以有涯隨無涯,殆①已!
  注: ①殆 :危險 作用(why):

編寫文檔:通過代碼裡標識的中繼資料產生文檔。
程式碼分析:通過代碼裡標識的中繼資料對代碼進行分析。
編譯檢查:通過代碼裡標識的中繼資料讓編譯器能實現基本的編譯檢查

我的理解:解釋代碼  元註解:  @Target 中 ElementType ( ElementType     ==> 範圍範圍):    1.CONSTRUCTOR:        用於描述構造器    2.FIELD:                         用於描述域    3.LOCAL_VARIABLE:    用於描述局部變數    4.METHOD:                    用於描述方法    5.PACKAGE:                  用於描述包    6.PARAMETER:             用於描述參數    7.TYPE:                       用於描述類、介面(包括註解類型) 或enum聲明  ElementType 的取值可以不止有一個,如下原碼: 
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface Autowired {    /**     * Declares whether the annotated dependency is required.     * <p>Defaults to {@code true}.     */    boolean required() default true;}
代碼的生命週期對應 @Retention    1   源碼(人可以識別的字元)階段  xx.java     2  編譯階段  xx.class     3  執行階段(被jvm載入交給CPU運行階段)byte[]    註解         SOURCE     對應源碼階段         CLASS        對應編譯階段         RUNTIME     隨時,包含上面兩個階段   應用情境1.編譯檢查        @SupperessWarnings2.在架構中使用,一般都會聲明為runtime        根據Annotation不同利用反射機制讀取出Annotation中的內容        從而根據不同的內容實現不同的邏輯3.根據Annotation產生協助文檔        @Document4.能夠協助我們提高代碼的識別度  @Override 

自訂註解(詳情見最上面代碼):

  使用@interface自訂註解時,自動繼承了java.lang.annotation.Annotation介面,由編譯器自動完成其他細節。在定義註解時,不能繼承其他的註解或介面。@interface用來聲明一個註解,其中的每一個方法實際上是聲明了一個配置參數。方法的名稱就是參數的名稱,傳回值類型就是參數的類型(傳回值類型只能是基本類型、Class、String、enum)。可以通過default來聲明參數的預設值。

  定義註解格式:
  public @interface 註解名 {定義體}

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

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

  Annotation類型裡面的參數該怎麼設定: 
  第一,只能用public或預設(default)這兩個訪問權修飾.例如,String value();這裡把方法設為defaul預設類型;   
  第二,參數成員只能用基本類型byte,short,char,int,long,float,double,boolean八種基礎資料型別 (Elementary Data Type)和 String,Enum,Class,annotations等資料類型,以及這一些類型的數組.例如,String value();這裡的參數成員就為String;  
  第三,如果只有一個參數成員,最好把參數名稱設為"value",後加小括弧。

 

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.