gpt4 book ai didi

java - 如何在运行时调用方法时忽略修饰符 - JAVA

转载 作者:行者123 更新时间:2023-11-30 03:36:44 25 4
gpt4 key购买 nike

我想查找类中每个方法的特定注释,如果找到带有该注释的方法,我想调用它。另外,如果在当前类中没有找到它,则应该检查所有继承类。

我的问题是,可能有一些方法是 protected 、私有(private)的等,我想忽略这些修饰符并获得对所有方法的访问权限(即即使它是私有(private)的等)

这就是我调用的方式(给出的是我正在寻找的注释的名称:

if (m.isAnnotationPresent(Given.class)) {
m.invoke(instObj, intArgument);
}

(这就是我检查类层次结构的其余部分的方法 - 如果我在某个地方犯了错误,请赐教:

Class<?> superC = c.getSuperclass();
while (!(superC.equals(Object.class))) {
handleGiven(instObj, superC, methods, currentSentence,
methodArgument);

handleGiven是递归调用时。

最佳答案

您需要使用getDeclaredMethods获取所有方法(公共(public)、 protected 等),如下所示:

public Method findMethodWithAnnotation(Class<?> clazz,
Class<? extends Annotation> annotation) {
for (Method m : clazz.getDeclaredMethods()) {
if (m.isAnnotationPresent(annotation)) {
return m;
}
}
return null;
}

并像这样检查:

    Class<?> clazz = ..; //get the class
Method m = null;
do {
m = findMethodWithAnnotation(clazz, DesiredAnnotation.class);
clazz = clazz.getSuperclass();
} while (m == null && clazz != null);
System.out.println(m);

还要确保您的注释具有以下注释:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)

如果需要字段注释,请查看 getDeclaredFields ,以及类似的方法。

您需要在调用之前使该方法可访问

m.setAccessible(true);
<小时/>

如果您想要更紧凑和递归的实现,您可以更改为:

public Method findMethodWithAnnotation(Class<?> clazz,
Class<? extends Annotation> annotation) {

if (clazz == Object.class || clazz == null) return null;
for (Method m : clazz.getDeclaredMethods()) {
if (m.isAnnotationPresent(annotation)) {
return m;
}
}
return findMethodWithAnnotation(clazz.getSuperClass(), annotation);
}

用途是:

Method m = findMethodWithAnnotation(clazz, DesiredAnnotation.class)
if (m == null) log("Nor the class, or any superclass have the desired annotation")
else {
m.setAccessitble(true);
m.invoke(obj, arguments);
}

注意事项:

  • 这里不覆盖接口(interface),如果需要覆盖接口(interface),请查看getInterfaces() (该方法按照声明的顺序返回接口(interface))。
  • 如果一个类A有一个重写方法desiredMethod,没有注释,并且扩展了一个类SuperA,那么它就有一个方法desiredMethod,带有所需的注释,返回SuperA#desiredMethod,但是当您调用它时,它将在A类中调用(就像普通调用一样) )

关于java - 如何在运行时调用方法时忽略修饰符 - JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27727266/

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