/**
* 日志注解
*/
@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());
}
}