Java 将一个类方法传递给另一个类方法

Java 将一个类方法传递给另一个类方法,java,Java,假设我有下面的课 class Application { public Application() {...} public void doSomething(final String logs) { final String[] lines = logs.split("\\n"); for (final String line: lines) { // Pass the line to every single check

假设我有下面的课

class Application {
    public Application() {...}

    public void doSomething(final String logs) {
        final String[] lines = logs.split("\\n");
        for (final String line: lines) {
           // Pass the line to every single checkForProp# item and do something with the response
        }
    } 

    private Optional<Action> checkForProp1(final String line) {
       // Check if line has certain thing
       // If so return an Action
    }

    // More of these "checks" here
}
类应用程序{
公共应用程序(){…}
公共无效数据量(最终字符串日志){
最终字符串[]行=logs.split(\\n”);
用于(最后一行字符串:行){
//将该行传递给每个checkForProp项目,并对响应进行处理
}
} 
私有可选checkForProp1(最后一行字符串){
//检查线路上是否有某些东西
//如果是,返回一个操作
}
//这里有更多的“支票”
}
假设每个响应都将被添加到队列中,然后返回在该队列上执行的操作

因此,我不想手动调用每个方法,而是希望有一个检查器方法数组,并自动循环它们,传入队列,然后将响应添加到队列中


这可以实现吗?

您可以将您的操作作为接口来实现:

public interface Action{
   public void fireAction();
}
实现操作的类将覆盖接口中定义的方法,例如检查字符串

将操作实例添加到列表中,并相应地循环它们

例如:

for(Action a : actions)
    a.fireAction();

如果我正确理解了您的问题,那么下面的代码可能会对您有所帮助

import java.lang.reflect.Method;
公共类AClass{

private void aMethod(){
    System.out.println(" in a");
}

private void bMethod(){
    System.out.println(" in b");
}

private void cMethod(){
    System.out.println(" in c");
}

private void dMethod(){
    System.out.println(" in d");
}

//50 more methods. 

//method call the rest
public void callAll() {
     Method[] methods = this.getClass().getDeclaredMethods();
    try{
    for (Method m : methods) {

        if (m.getName().endsWith("Method")) {
            //do stuff..
            m.invoke(this,null);
        }
    }
    }catch(Exception e){

    }
}
 public static void main(String[] args) {
AClass a=new AClass();
a.callAll();
 }
    }

这里使用Java反射。

您可以使用
接口
为此,您可能会创建一个接口并创建一个类,您将不得不为每一个实例创建实例,手动添加检查可能更容易一些?如果检查顺序不重要,那么您可能会使用一些注释来“标记”检查并进行一些反射以调用它们(找到用@XXX注释的方法,然后调用它们)@RC我喜欢注释方法!