【问题标题】:Call a method with arguments by a variable if argument type is unknown如果参数类型未知,则通过变量调用带有参数的方法
【发布时间】:2015-01-08 10:46:56
【问题描述】:

如果参数的数量和参数类型已知,我可以通过变量名调用带有参数的方法,但是如果只有在搜索时才知道参数和参数类型,如何获取声明的方法[搜索方法 ]。

public static void invokeMethod (String myClass, 
                                 String myMethod,  
                                 Class[] params, Object[] args)
                           throws Exception {
   Class c = Class.forName(myClass);
   Method m = c.getDeclaredMethod(myMethod, params);
   Object i = c.newInstance();
   Object r = m.invoke(i, args);

}

invokeMethod("myLib", "sampleMethod", new Class[] {String.class, String.class},
       new Object[]
         {new String("Hello"), new String("World")});

如果我不知道Class[] 的数量和类型怎么办?如何动态管理?我将通过命令行或套接字获取参数和方法。所以我不知道将接收哪种方法。

编辑- 我尝试了以下事情-

Class[] css = new Class[10] ;
Object[] obj = new Object[10];
                int argLn = params.length;
            if (argLn > 1) {

                func = params[0].trim();
                for (int Idx = 1; Idx < argLn; ++Idx) {

                    arg.add(params[Idx]);
                    try {
                        Integer.parseInt((params[Idx]));
                        css[Idx-1] = String.class;
                    } catch (NumberFormatException ne) {
                        css[Idx-1] = int.class;

                    }
                }

但最终出现异常-NoSuchMethodException。

【问题讨论】:

  • 你知道如何动态地创建和填充一个数组(而不是只写在源代码中)吗?
  • 我编辑了问题。
  • 既然您已经发布了一些代码,我认为此 Stack Overflow 指南适用:“寻求调试帮助的问题(“为什么此代码不起作用?”)必须包含所需的行为,特定问题或错误以及在问题本身中重现它所需的最短代码。”您那里的代码 sn-p 并不能很好地说明您在做什么。
  • 对不起,我是新来的,谢谢,我会跟上指导方针:)

标签: java reflection


【解决方案1】:

这在 Oracle 教程网站上进行了处理 - 请参阅关于反射的一般教程的 "Obtaining Method Type Information" 部分。

总之——在你打电话之后

Method m = c.getDeclaredMethod(myMethod, params);

你需要这样的东西:

Class<?>[] pType  = m.getParameterTypes();

和/或(取决于您的方法是否可能在其参数类型中使用泛型)

Type[] gpType = m.getGenericParameterTypes();

返回数组的长度将为您提供参数的数量、成员的类或类型。您可以将 pType 数组直接传递给您的 invokeMethod() 方法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-09
    • 1970-01-01
    • 2022-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多