调用类中的所有方法

sar*_*Fly 2 java reflection

我有一个类,它有一个方法调用同一个类中的所有其余方法.

一种方法是使用反射框架,还有其他方法吗?

[编辑]添加的示例代码:


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种方法,你会逐一称呼它们吗?我没有答案,这就是我在这里提问的原因.

谢谢,莎拉

Sea*_*oyd 5

实际上,你可能想要使用Class.getDeclaredMethods().Class.getMethods()只返回公共方法,并且您显示的方法都不是公共的(并且它还返回从超类继承的公共方法).

这就是说:在你提到的场景中,反射是一种有效的方法.所有其他(手动)方法都容易出错.

但是,使用命名约定对我来说似乎很弱.我会写一个自定义注释,如果存在,我会执行该方法.例:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RunMe {}
Run Code Online (Sandbox Code Playgroud)

这是你修改过的代码:

public void callAll() throws
IllegalArgumentException, IllegalAccessException, InvocationTargetException{
    Method[] methods = this.getClass().getDeclaredMethods();
    for (Method m : methods) {
        if (m.getAnnotation(RunMe.class)!=null) {
            //do stuff..
        }
    }
}
Run Code Online (Sandbox Code Playgroud)