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

asked Oct 21, 2011 at 22:21
1
  • not yet; we'll have to wait for java 8 for that feature Commented Oct 22, 2011 at 3:31

4 Answers 4

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 );
answered Oct 21, 2011 at 22:22
Sign up to request clarification or add additional context in comments.

3 Comments

Sorry I'm still pretty new to Java. Could you elaborate on that for me?
@QuanChi: Elaborate on what part?
@QuanChi Please see the duplicate question in the question comments.
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.

answered Oct 21, 2011 at 22:23

1 Comment

Yes you could do this, at the expense of some nasty code and loss of type safety
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();
 }
});
answered Oct 21, 2011 at 22:32

Comments

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);
 }
}
answered Oct 21, 2011 at 22:40

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.