Kousha
Kousha

Reputation: 36219

Pass a class method to another class method

Say I have the following class

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
}

Let's say every single response, would be added to a queue, and then returned something is done on that queue.

So instead of I calling each method manually, I want to have maybe an array of checker methods, and automatically loop through them, pass in the line, and add the response to a queue.

Can this be achieved?

Upvotes: 1

Views: 82

Answers (2)

user3437460
user3437460

Reputation: 17454

You can implement your Action as interface:

public interface Action{
   public void fireAction();
}

Those classes which implement Action will then override the method defined in the interface, such as checking a String.

Add the instances of Action to the list and you loop them accordingly.

Example:

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

Upvotes: 2

Tejendra
Tejendra

Reputation: 159

If i understood your question correctly then following code may be help you.

import java.lang.reflect.Method;

public class 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();
 }
    }

Here Java Reflection is used.

Upvotes: 0

Related Questions