【发布时间】:2011-08-10 02:48:33
【问题描述】:
我想得到一个类似这样的 Method 对象:
Method myMethod = MyClass.class.getDeclaredMethod("myDeclaredMethod",Arg1Class.class);
但是!我想在编译时检查方法“myDeclaredMethod”是否存在。我实际上不需要动态选择方法,我只需要对它的引用,这样我就可以将它传递给另一个方法……类似于 C 具有函数指针的方式。我想做这样的事情:
#include <stdio.h>
void helloWorld() {
printf("hello\n");
}
void runFunction( void (myfunc)() ) {
myfunc();
}
int main() {
runFunction(helloWorld);
return 0;
}
注意,如果我在调用“runFunction(helloWorld)”中输入错误“helloWorld”,我会收到编译时错误。如果可能的话,我希望在 Java 中出现同样的编译时错误。
【问题讨论】:
标签: java reflection