我有一个类,其中有一个方法调用同一类中的所有其余方法。
一种方法是使用反射框架,还有其他方法吗?
[编辑] 添加示例代码:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class AClass {
private void aMethod(){
}
private void bMethod(){
}
private void cMethod(){
}
private void dMethod(){
}
//50 more methods.
//method call the rest
public void callAll() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException{
Method[] methods = this.getClass().getMethods();
for (Method m : methods) {
if (m.getName().endsWith("Method")) {
//do stuff..
}
}
}
}
实际上,我从 callAll() 调用所有 4 个方法没有问题,即避免使用反射。但我的一位同事指出,如果有50个方法怎么办,你要一一调用吗?我对此没有答案,这就是我在这里问这个问题的原因。
谢谢, 莎拉
最佳答案
实际上,您可能想使用 Class.getDeclaredMethods()
。 Class.getMethods()
只返回公共(public)方法,并且您显示的方法都不是公共(public)的(并且它还返回从父类(super class)继承的公共(public)方法)。
也就是说:在您提到的场景中,反射是一种有效的方法。所有其他(手动)方法都容易出错。
但是,作为一名 guard ,使用命名约定对我来说似乎很弱。我会编写一个自定义注释,如果存在,我会执行该方法。示例:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RunMe {}
这是您修改后的代码:
public void callAll() throws
IllegalArgumentException, IllegalAccessException, InvocationTargetException{
Method[] methods = this.getClass().getDeclaredMethods();
for (Method m : methods) {
if (m.getAnnotation(RunMe.class)!=null) {
//do stuff..
}
}
}
关于java - 调用类中的所有方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4778238/