调用名为“string"的方法在 Java 和 C 中运行时 [英] Calling a method named "string" at runtime in Java and C

查看:7
本文介绍了调用名为“string"的方法在 Java 和 C 中运行时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何在运行时调用名称为 string 的方法.谁能告诉我如何用 Java 和 C 来做到这一点.

How can we call a method which name is string at runtime. Can anyone show me how to do that in Java and C.

推荐答案

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

In java it can be done through the reflection api.

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

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

A complete example (of a non-static method with an argument) would be:

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

输出:

Hello World: 5

这篇关于调用名为“string"的方法在 Java 和 C 中运行时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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