自定义注解---反射获取注解案例

自定义注解:

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();
        }
    }
}


 

猜你喜欢

转载自blog.csdn.net/qq_38244874/article/details/82180743