繁体   English   中英

如果参数类型未知,则通过变量调用带有参数的方法

[英]Call a method with arguments by a variable if argument type is unknown

如果参数和参数类型的数目已知,我可以通过变量名称调用带有参数的方法,但是如果仅在search [search for method]时参数和参数类型未知,那么如何获取声明的方法。

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

这在Oracle教程网站上进行了处理-请参见反射常规教程的“获取方法类型信息”部分。

总结-致电后

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

您需要这样的东西:

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

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

Type[] gpType = m.getGenericParameterTypes();

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM