自定义注解
@Target(value = {ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value();
}
使用自定义注解
@MyAnnotation(value = "service")
public class UserService {
String name;
@MyAnnotation("yingying")
public static void sm() {
System.out.println("UserService类中的sm方法被执行了");
}
}
注解+反射的应用
public class Test {
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class<UserService> userServiceClass = UserService.class;
MyAnnotation annotation = userServiceClass.getAnnotation(MyAnnotation.class);
if (annotation != null) {
System.out.println(annotation.value());
}
Method sm = userServiceClass.getMethod("sm");
MyAnnotation smAnnotation = sm.getAnnotation(MyAnnotation.class);
if (smAnnotation != null) {
String value = smAnnotation.value();
if ("yingying".equals(value)) {
sm.invoke(null);
}
}
}
}