getting a method object for a class with compile time checking (in java)

我只是一个虾纸丫 提交于 2020-01-24 08:21:30

问题


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.


回答1:


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




回答2:


This is not possible in Java: methods are not first-class citizens in Java.

But it is possible to do in Scala!




回答3:


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())



来源:https://stackoverflow.com/questions/6960070/getting-a-method-object-for-a-class-with-compile-time-checking-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!