简体   繁体   English

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

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

I am able invoke a method with arguments by a variable name if number of arguments and argument types are known, But how to get the declared method if no if arguments and argument type are known only at the time of search[search for method ]. 如果参数和参数类型的数目已知,我可以通过变量名称调用带有参数的方法,但是如果仅在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")});

What if I am not aware of the count and type of Class[] ? 如果我不知道Class[]的数量和类型怎么办? How to manage this dynamically? 如何动态管理? I will get the arguments and method through the command line or a socket. 我将通过命令行或套接字获取参数和方法。 So I am not aware that which method will be receiving. 因此,我不知道将采用哪种方法。

Edit- I tried below things- 编辑-我在下面尝试了-

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;

                    }
                }

But ended up in exception- NoSuchMethodException . 但是最终导致异常NoSuchMethodException

This is dealt with on the Oracle tutorials website - see "Obtaining Method Type Information" part - of the general tutorial on reflection. 这在Oracle教程网站上进行了处理-请参见反射常规教程的“获取方法类型信息”部分。

In summary - after you call 总结-致电后

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

you need something like this: 您需要这样的东西:

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

and/or (depending whether your methods might use generics in their parameter types) 和/或(取决于您的方法是否在其参数类型中使用泛型)

Type[] gpType = m.getGenericParameterTypes();

The length of the returned array will give you the number of parameters, the members their class or type. 返回数组的长度将为您提供参数数量,成员的类或类型。 You can pass the pType array straight to your invokeMethod() method 您可以将pType数组直接传递给invokeMethod()方法

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

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