I would like to get a Method object similar to this:
Method myMethod = MyClass.class.getDeclaredMethod("myDeclaredMethod",Arg1Class.class);
But! I would like compile time checking of the existence of the method “myDeclaredMethod”. I don’t actually need to dynamically choose the method, I just need a reference to it so I can pass it to another method… similar to the way C has function pointers. I’d like to do something like this:
#include <stdio.h>
void helloWorld() {
printf("hello\n");
}
void runFunction( void (myfunc)() ) {
myfunc();
}
int main() {
runFunction(helloWorld);
return 0;
}
Notice, if I mistype “helloWorld” in the call “runFunction(helloWorld)”, I get a compile time error. I want that same compile time error in Java, if possible.
I’m afraid you can’t do that in Java.
However, the usual way to achieve this in Java is to define an interface that will declare only one method, the one you want to “pass as argument”, and implement it in a class. Your class has to implement the method you are interested in. When you want to pass a “reference” to the method, you actually pass an instance of your interface. You can call your method on it.
An example might explain this:
The problem is, if you want to call another method you need to create a new class implementing
Something