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

7次阅读

共计 946 个字符,预计需要花费 3 分钟才能阅读完成。

自定义注解

/**
 * 日志注解
 */

@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());
        }
    }
正文完
 0