X
X
XiNull2019-07-27 05:45:06
Java
XiNull, 2019-07-27 05:45:06

How to pass a method to another method?

It is necessary that method_1 accept any other method (for any data processing in method_1) and one more argument (data), and then this any method could be used in the main method_1.
public void method_1(String data, Random_method) {
Random_method(data);
}
method_1("Some data...", Random_method);
How can such a thing be implemented?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2019-07-27
@XiNull

public class Example {
    private void method1(String data, Consumer<String> method) {
        method.accept(data);
    }

    private void method2(String data) {
        System.out.println(data);
    }

    public static void main(String[] args) {
        Example obj = new Example();
        obj.method1("test", obj::method2);
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question