1. 程式人生 > >自定義註解---反射獲取註解案例

自定義註解---反射獲取註解案例

自定義註解:

package Demo01;

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

@Target(value = ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Over {
    String name() default "";

    int age() default -1;
}

反射獲取註解:

package Demo01;

import java.lang.annotation.Annotation;

@Over(name = "張三", age = 18)
public class Demo1 {
    public static void main(String[] args) {
        Demo1 dd = new Demo1();
        dd.test1("張琳");

    }

    public void test1(String name) {
        try {
            // 獲得這個類的類物件
            Class clazz = this.getClass().forName("Demo01.Demo1");
            // 判斷類上是否有此註解
            boolean exit = clazz.isAnnotationPresent(Over.class);
            System.out.println(exit);

            // 得到註解陣列
            Annotation[] annotation = clazz.getAnnotations();
            // 遍歷陣列
            for (Annotation a : annotation) {
                // 獲得註解上的屬性;
                int age1 = ((Over) a).age();
                String s1 = ((Over) a).name();
                System.out.println(s1 + ":" + age1);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}