通过反射获取注解

自定义注解

/**
 * 日志注解
 */

@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());
        }
    }
原文地址:https://www.cnblogs.com/PoetryAndYou/p/14557376.html