3

I want to make a method that does a specific task, but then calls another method with the results of that task. Well easy enough, but the trick is that I want the method (the second one thats getting called by the first one) to be a parameter of the first method.

I probably explained that terribly, so here is what I think it might look like

public static void main(String[] args) {
    double[][] data = {
        {2,6},
        {-32,5}
    }

    loop(data,{System.out.println(row * col)});
}

public static void loop(double[][] data,somemethod(row,col)) {
    for (int row = 0;row < data.length;row++)
        for (int col = 0;col < data[0].length;col++)
            somemethod(row,col);
}

So the loop method does a task, and then runs the code that was passed as a parameter. Can this be done in java? I feel like I have seen it somewhere.

Hurricane Development
  • 2,449
  • 1
  • 19
  • 40

3 Answers3

5

The pre-Java-8 way to do this was by creating an interface with the method you want called:

interface MyCallback {
    void someMethod(int row, int col);
}

You create an object with the implementation you want:

class MyCallbackImpl implements MyCallback {

    public void somemethod(int row, int col) {
        System.out.println(row * col);
    }
}

and have the method take a parameter implementing that interface:

public static void loop(double[][] data, MyCallback mycallback) {
    for (int row = 0;row < data.length;row++)
        for (int col = 0;col < data[0].length;col++)
            mycallback.somemethod(row,col);
}

If you'd rather not create a separate named class for this you have the alternative of creating an object using an anonymous inner class, calling your loop method like:

loop(data, new MyCallback() {
    public void somemethod(int row, int col) {
        System.out.println(row * col);
    }});
Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
0

In Java 8 the Lambda expressions make that possible. It was not possible before. This is what I know.

muasif80
  • 5,586
  • 4
  • 32
  • 45
0

You can use Reflection to do this trick!

First, you find the method like this:

java.lang.reflect.Method method;
try {
  method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);
} catch (SecurityException e) {
  // ...
} catch (NoSuchMethodException e) {
  // ...
}

In your case, you will send methodName and the parameters of methodName as parameters of loop class. After finding the method, you execute it as:

try {
  method.invoke(param1, param1,...);
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {

Hope it helps...

Laerte
  • 7,013
  • 3
  • 32
  • 50