Java, store method reference for later execution

Florian Castelain :

In java 8, I would like to store method reference.

The context is: my program may not be able to execute methods right now but must execute them before it terminates. So my objective is to store these methods in a dedicated class that will execute them before program terminates.

So far, here is what I tried:

I have an interface that matches what the method prototype should be:

public interface IExecutable {
    public void method(String[] args);
}

I have a class that is supposed to store methods and their arguments:

import java.util.HashMap;
import java.util.Map;

public class LateExecutor {

    private Map<String[], IExecutable> tasks = new HashMap<>();

    public void execute() {
        tasks.forEach((args, method) -> method(args));
    }

    public void storeTask(String[] args, IExecutable method) {
        tasks.put(args, method);
    }
}

With this, I wanted to call storeTask with something like this, from another class:

lateExecutor.storeTask(arrayOfArgs, object::method)

But with the current state of the LateExecutor class, I have the following error on -> method(:

The method method(String[]) is undefined for the type LateExecutor

Which I understand because LateExecutor does not have this method.

However that leaves me with the following problem: How to store method reference and execute them later (Any other idea to solve my problem is also welcomed).

ernest_k :

Your map has instances of IExecutables, and that's how you should treat them:

public void execute() {
    //better rename "method" to something like "executable"
    tasks.forEach((args, method) -> method.method(args));
}

The method parameter in the forEach lambda expression is an IExecutable, and the name of the method in that interface is method.


Side note: you shouldn't need to declare IExecutable. There's a built-in functional interface with that method signature: you can use Consumer<String[]> (then accept(args) would be how you invoke the method)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=170363&siteId=1