0

Is it possible to specify a method as a method parameter?

e.g.

public void someMethod(String blah, int number, method MethodName)

Where MethodName is the name of a different method that needs to be specified.

Thanks

Blackvein
  • 558
  • 4
  • 10
  • 23

4 Answers4

1

No, but you specify an interface with a single method. And you can pass an anonymous implementation to the method

interface CompareOp {
  int compare(Object o1, Object o2);
}

// Inside some class, call it Klass
public static int compare ( CompareOp comparator, Object o1, Object o2) {
   return comparator.compare(o1, o2);
}

Then you would call it like

Klass.compare( new CompareOp(){
  public int compare(Object o1, Object o2) {
    return o1.hashCode() - o2.hashCode();
  }
}, obj1, obj2 );
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
1

Using reflection, it is possible to pass Method as parameter. you can get more info from the java tutorial. It is not exactly like you did. I suggest you consider the options in the question that linked as possible duplicate before starting to use reflecion.

Community
  • 1
  • 1
oshai
  • 14,865
  • 26
  • 84
  • 140
0

If you want someMethod to call MethodName, then you should use a callback interface :

public interface Callback {
    void callMeBack();
}

// ...

someObject.someMethod("blah", 2, new Callback() {
    @Override
    public void callMeBack() {
        System.out.println("someMethod has called me back. I'll call methodName");
        methodName();
    }
});
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

With reflection even the following code is possible:

import java.lang.reflect.Method;

public class Test {

    public static void main(final String a[]) {
        execute("parameter to firstMethod", "firstMethod");
        execute("parameter to secondMethod", "secondMethod");
    }

    private static void execute(final String parameter, final String methodName) {
        try {
            final Method method = Test.class.getMethod(methodName, String.class);
            method.invoke(Test.class, parameter);
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }

    public static void firstMethod(final String parameter) {
        System.out.println("first Method " + parameter);
    }

    public static void secondMethod(final String parameter) {
        System.out.println("first Method " + parameter);
    }

}
Francisco Spaeth
  • 23,493
  • 7
  • 67
  • 106