在Java和C中在运行时调用名为"string"的方法

dbt*_*tek 5 c java string methods runtime

我们如何在运行时调用名称为string的方法.任何人都可以告诉我如何在Java和C中做到这一点

aio*_*obe 26

在java中,它可以通过反射api完成.

看看Class.getMethod(String methodName, Class... parameterTypes).

一个完整的例子(带有参数的非静态方法)将是:

import java.lang.reflect.*;
public class Test {

    public String methodName(int i) {
        return "Hello World: " + i;
    }

    public static void main(String... args) throws Exception {
        Test t = new Test();
        Method m = Test.class.getMethod("methodName", int.class);
        String returnVal = (String) m.invoke(t, 5);
        System.out.println(returnVal);
    }
}
Run Code Online (Sandbox Code Playgroud)

哪个输出:

Hello World: 5