java註解annotation,自訂註解

來源:互聯網
上載者:User

標籤:

定義:

package com.dxz.annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;//定義註解@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD,        ElementType.LOCAL_VARIABLE })@Retention(RetentionPolicy.RUNTIME)public @interface MyAnnotation {    // 定義兩個成員變數    String name() default "jack";    int age() default 22;}

測試:

package com.dxz.annotation;import java.lang.annotation.Annotation;/* * 獲得註解資訊要注意,當前註解一定要保留在RUNTIME *  * 獲得註解資訊方法: * 1.getAnnotations() * 調用註解成員變數 * 1.假設註解對象ann,調用成員變數方式:ann.name(); * 2.與調用類方法類似 */public class TestAnnotationInfo {        public static void main(String[] args) {        TestAnnotationInfo tai = new TestAnnotationInfo();        try {            tai.getInfo();        } catch (NoSuchMethodException e) {            e.printStackTrace();        } catch (SecurityException e) {            e.printStackTrace();        }    }    @MyAnnotation(name = "zhangxun", age = 20)    public void getInfo() throws NoSuchMethodException, SecurityException {        // 擷取TestAnnotationInfo對象的getInfo()方法中包含的所有註解        @MyAnnotation        Annotation[] annos = TestAnnotationInfo.class.getMethod("getInfo")                .getAnnotations();        // 遍曆annos數組        for (Annotation ann : annos) {            // ann就是一個Annotation 對象            // 判斷當前ann是否是MyAnnotation註解類型            if (ann instanceof MyAnnotation) {                System.out.println(ann);                System.out.println(((MyAnnotation) ann).name());                System.out.println(((MyAnnotation) ann).age());            }        }    }}

 

java註解annotation,自訂註解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.