调用命名的方法"串QUOT;在Java和C运行时 [英] Calling a method named "string" at runtime in Java and C

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

问题描述

我们如何可以调用的名称为字符串在运行时的方法。谁能告诉我怎么做,在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.

看一看<一个href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getMethod%28java.lang.String,%20java.lang.Class...%29\"><$c$c>Class.getMethod(String方法名,类... 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

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

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