java - 调用类中的所有方法

标签 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个方法怎么办,你要一一调用吗?我对此没有答案,这就是我在这里问这个问题的原因。

谢谢, 莎拉

最佳答案

实际上,您可能想使用 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/

相关文章:

java - 仅更改 ioc 容器中大型依赖关系图中的一个依赖关系以进行测试

java - 如何比较两个类

reflection - Dart 中的动态实例化

c# - 类扩展 - 最佳实践/最佳解决方案

使用 Objenesis 创建静态内部类实例时出现 java.lang.InstantiationError

c# - .NET 反射 : how do I loop through an object that is an array type?

java - 将 ExplicitWait 方法调用到功能特性中

java - DateTimeFormatter异常解析其自己的打印结果

java - 我们如何使用任何 Java API 将 WMF/EMF(MS 图元文件)转换为 JPG 或 PNG 等标准图像?

java - 扩展 Java 类并强制现有库使用扩展类