gpt4 book ai didi

Java 寻找具有特定注解的方法及其注解元素

转载 作者:IT老高 更新时间:2023-10-28 20:51:23 24 4
gpt4 key购买 nike

假设我有这个注解类


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MethodXY {
public int x();
public int y();
}

public class AnnotationTest {
@MethodXY(x=5, y=5)
public void myMethodA(){ ... }

@MethodXY(x=3, y=2)
public void myMethodB(){ ... }
}

那么有没有办法查看一个对象,“寻找”带有@MethodXY 注释的方法,其中它的元素x = 3,y = 2,然后调用它?

谢谢

最佳答案

这是一个方法,它返回带有特定注释的方法:

public static List<Method> getMethodsAnnotatedWith(final Class<?> type, final Class<? extends Annotation> annotation) {
final List<Method> methods = new ArrayList<Method>();
Class<?> klass = type;
while (klass != Object.class) { // need to traverse a type hierarchy in order to process methods from super types
// iterate though the list of methods declared in the class represented by klass variable, and add those annotated with the specified annotation
for (final Method method : klass.getDeclaredMethods()) {
if (method.isAnnotationPresent(annotation)) {
Annotation annotInstance = method.getAnnotation(annotation);
// TODO process annotInstance
methods.add(method);
}
}
// move to the upper class in the hierarchy in search for more methods
klass = klass.getSuperclass();
}
return methods;
}

它可以根据您的特定需求轻松修改。请注意,提供的方法会遍历类层次结构,以便找到具有所需注释的方法。

这是满足您特定需求的方法:

public static List<Method> getMethodsAnnotatedWithMethodXY(final Class<?> type) {
final List<Method> methods = new ArrayList<Method>();
Class<?> klass = type;
while (klass != Object.class) { // need to iterated thought hierarchy in order to retrieve methods from above the current instance
// iterate though the list of methods declared in the class represented by klass variable, and add those annotated with the specified annotation
for (final Method method : klass.getDeclaredMethods()) {
if (method.isAnnotationPresent(MethodXY.class)) {
MethodXY annotInstance = method.getAnnotation(MethodXY.class);
if (annotInstance.x() == 3 && annotInstance.y() == 2) {
methods.add(method);
}
}
}
// move to the upper class in the hierarchy in search for more methods
klass = klass.getSuperclass();
}
return methods;
}

对于找到的方法的调用请引用 tutorial .这里的潜在困难之一是方法参数的数量,它可能因找到的方法而异,因此需要一些额外的处理。

关于Java 寻找具有特定注解的方法及其注解元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6593597/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com