使用Java自定义注解实现不同目标方法执行不同逻辑
时间: 2023-12-10 12:03:36 浏览: 37
要实现不同目标方法执行不同逻辑,可以使用Java自定义注解和反射机制。
首先,自定义注解需要用@Target注解来指定使用范围,例如可以指定在方法上使用,即@Target(ElementType.METHOD)。
其次,注解需要用@Retention注解来指定生命周期,例如可以指定在运行时依然存在,即@Retention(RetentionPolicy.RUNTIME)。
然后,在目标方法上加上自定义注解,并通过反射获取注解信息,根据注解信息执行不同逻辑。
下面是一个简单的示例代码:
```
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value();
}
public class AnnotationDemo {
@MyAnnotation("method1")
public void method1() {
System.out.println("This is method1");
}
@MyAnnotation("method2")
public void method2() {
System.out.println("This is method2");
}
public static void main(String[] args) throws Exception {
AnnotationDemo demo = new AnnotationDemo();
Method[] methods = demo.getClass().getDeclaredMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
if (annotation.value().equals("method1")) {
method.invoke(demo);
} else if (annotation.value().equals("method2")) {
method.invoke(demo);
}
}
}
}
}
```
在上面的示例代码中,定义了一个自定义注解@MyAnnotation,并在AnnotationDemo类中的两个方法上分别加上了该注解,并指定了不同的value值。
在main方法中,通过反射获取AnnotationDemo类中的所有方法,判断方法上是否加上了@MyAnnotation注解,如果有,则获取注解信息,并根据注解信息执行不同的逻辑。
在这个简单的例子中,我们可以看到使用自定义注解和反射机制可以实现不同目标方法执行不同逻辑的功能。