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 pointe开发者_如何学Pythonrs. 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:
interface Something {
void doSomething();
}
class HelloWorld {
void doSomething() {
System.out.println("Hello world");
}
}
class Main {
void runFunc(Something s) {
s.doSomething();
}
public static void main(String... args) {
runFunc(new HelloWorld());
}
}
The problem is, if you want to call another method you need to create a new class implementing Something
This is not possible in Java: methods are not first-class citizens in Java.
But it is possible to do in Scala!
You could write an annotations processor which using private APIs in the JDK check the the methods invoked via the reflection API and occassionally halt the compilation process.
This is detailed in Compile-Time Checked Reflection API as is done by dp4j.
If you use dp4j with @Reflect or JUnit's @Test annotations you get the compile-time checking when you call the method 'normally', as in myDeclaredMethod(new Arg1Class())
精彩评论