使用编译时检查获取类的方法对象(在 Java 中) [英] getting a method object for a class with compile time checking (in java)

查看:32
本文介绍了使用编译时检查获取类的方法对象(在 Java 中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想得到一个类似于这样的 Method 对象:

I would like to get a Method object similar to this:

Method myMethod = MyClass.class.getDeclaredMethod("myDeclaredMethod",Arg1Class.class);

但是!我想在编译时检查方法myDeclaredMethod"是否存在.我实际上不需要动态选择方法,我只需要对它的引用,以便我可以将它传递给另一个方法......类似于 C 具有函数指针的方式.我想做这样的事情:

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;
}

注意,如果我在调用runFunction(helloWorld)"中输入错误的helloWorld",我会得到一个编译时错误.如果可能,我希望在 Java 中出现相同的编译时错误.

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.

推荐答案

恐怕你不能在 Java 中做到这一点.

I'm afraid you can't do that in Java.

然而,在 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());
    }

}

问题是,如果你想调用另一个方法,你需要创建一个实现 Something

The problem is, if you want to call another method you need to create a new class implementing Something

这篇关于使用编译时检查获取类的方法对象(在 Java 中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆