java自定義註解demo

1.定義註解

package com.wxd.study1.study.study20200310;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyFirstAnnotation {

      String name() default "wxd";

      int age() default 18;
}

2.將註解放在類或者方法上

package com.wxd.study1.study.study20200310;

@MyFirstAnnotation(name = "wxd類註釋",age = 21)
public class MethodClass {

    @MyFirstAnnotation(name = "wxd方法註釋")
    public void test1(){
        System.out.println(123);
    }
    @MyFirstAnnotation(name = "ggg",age = 22)
    public void ttt2(){
        System.out.println(123312312);
    }
}

3.在main方法中測試

package com.wxd.study1.study.study20200310;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class Test {
    public static void main(String[] args) {

        Class aClass = MethodClass.class;
        Annotation[] annotations = aClass.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }
        Method[] methods = aClass.getDeclaredMethods();
        for (Method method : methods) {
            System.out.println(method);
            System.out.println(method.getName());
        }
        Annotation annotation = aClass.getAnnotation(MyFirstAnnotation.class);
        System.out.println("---------"+annotation);
        System.out.println("---------------------------------------#########################");
        MyFirstAnnotation annotation1 = MethodClass.class.getAnnotation(MyFirstAnnotation.class);
        System.out.println(annotation1.name());
        System.out.println(annotation1.age());
        Method[] declaredMethods = MethodClass.class.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            System.out.println(declaredMethod.getAnnotation(MyFirstAnnotation.class).age());
            System.out.println(declaredMethod.getAnnotation(MyFirstAnnotation.class).name());
            System.out.println(declaredMethod.getName());
        }
    }
}

4:輸出

@com.wxd.study1.study.study20200310.MyFirstAnnotation(name=wxd類註釋, age=21)
public void com.wxd.study1.study.study20200310.MethodClass.ttt2()
ttt2
public void com.wxd.study1.study.study20200310.MethodClass.test1()
test1
[email protected](name=wxd類註釋, age=21)
---------------------------------------#########################
wxd類註釋
21
22
ggg
ttt2
18
wxd方法註釋
test1

注意: class.getAnnotation(Class<A> annotationClass)方法中,前面爲使用的註解的類class,括號中的參數爲註解的class

如上就是MethodClass.class.getAnnotation(MyFirstAnnotation.class);

MethodClass爲使用了註解的類,

MyFirstAnnotation爲創建的註解類。否則能方法獲取的Annotation對象爲null

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章