如何在运行时调用方法时忽略修饰符-JAVA
我想查找类中每个方法的特定注释,如果找到带有该注释的方法,我想调用它。 此外,如果在当前类中找不到它,则应检查所有继承类 我的问题是,可能有一些方法是受保护的、私有的等,我希望忽略这些修饰符并获得对所有方法的访问权(即即使它是私有的等)。 这就是我调用的方式(给定的是我要查找的注释的名称):如何在运行时调用方法时忽略修饰符-JAVA,java,oop,reflection,Java,Oop,Reflection,我想查找类中每个方法的特定注释,如果找到带有该注释的方法,我想调用它。 此外,如果在当前类中找不到它,则应检查所有继承类 我的问题是,可能有一些方法是受保护的、私有的等,我希望忽略这些修饰符并获得对所有方法的访问权(即即使它是私有的等)。 这就是我调用的方式(给定的是我要查找的注释的名称): if (m.isAnnotationPresent(Given.class)) { m.invoke(instObj, intArgument); } (这就是我检查类层次结构其余部分的
if (m.isAnnotationPresent(Given.class)) {
m.invoke(instObj, intArgument);
}
(这就是我检查类层次结构其余部分的方式-如果我在某个地方出错,请告诉我:
Class<?> superC = c.getSuperclass();
while (!(superC.equals(Object.class))) {
handleGiven(instObj, superC, methods, currentSentence,
methodArgument);
Class super=c.getSuperclass();
而(!(super.equals(Object.class))){
handleGiven(instObj、superC、方法、当前句子、,
方法论;
当handleGiven
是递归调用时。您需要使用以获取所有方法(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);
如果需要字段的注释,请检查、和similar方法
在调用之前,您需要使该方法可访问
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);
}
考虑事项:
- 这不包括接口,如果需要包括接口,请选中(此方法按声明顺序返回接口)
- 如果一个类
有一个覆盖方法a
,没有注释,并且扩展了一个类desiredMethod
,witch有一个方法SuperA
,带有所需注释,则返回desiredMethod
,但是当您调用它时,它将在SuperA#desiredMethod
类中调用(就像一个普通的调用)a
你需要在调用它之前调用它,不要忘记在最后一个块中恢复它的原始值。你在寻找吗?实际上我使用了getMethods。妈的,我想你是对的。有没有一种简单的非递归方法来检查所有的内置类方法呢?
getMethods
只返回公共类;getDe>claredMethods
返回了所有的方法。真不敢相信这有那么愚蠢。那么非递归方法呢?你知道吗?这是否意味着我的impl.是错误的,或者它只是另一个解决方案(对于递归部分)不,你的解决方案没有错,这只是完整的实现。
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);
}