关于java:通过反射获取注解内容

自定义注解

/**
 * 日志注解
 */

@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
    String value() default "";
}

应用注解的类

@Component
@Log("小明呀")
public class TargetclassTest {

    @Log("小明")
    public void getMoney(String name, String money) {
//        int i = 1/0;
        System.out.println(name + "有" + money + "元");
    }
}

获取办法上的注解

    /**
     * 通过反射获取办法上的注解
     */
    @Test
    public void reflectionAnnotationMethod() throws NoSuchMethodException {
        Class clazz = TargetclassTest.class;
        Method getMoney = clazz.getDeclaredMethod("getMoney", String.class, String.class);
        if (getMoney.isAnnotationPresent(Log.class)) {
            Log declaredAnnotation = getMoney.getDeclaredAnnotation(Log.class);
            System.out.println(declaredAnnotation.value());
        }
    }

获取类上的注解

    /**
     * 通过反射获取类上的注解
     */
    @Test
    public void reflectionAnnotationClass() throws NoSuchMethodException {
        Class clazz = TargetclassTest.class;
        if (clazz.isAnnotationPresent(Log.class)) {
            Log declaredAnnotation = (Log) clazz.getDeclaredAnnotation(Log.class);
            System.out.println(declaredAnnotation.value());
        }
    }

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理