如果参数类型未知,则通过变量调用带参数的方法 [英] Call a method with arguments by a variable if argument type is unknown

查看:41
本文介绍了如果参数类型未知,则通过变量调用带参数的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 ].

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[] 的数量和类型怎么办?如何动态管理这个?我将通过命令行或套接字获取参数和方法.所以我不知道哪个方法会被接收.

What if I am not aware of the count and type of 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;

                    }
                }

但最终出现异常 - NoSuchMethodException.

But ended up in exception- NoSuchMethodException.

推荐答案

这在 Oracle 教程网站上进行了处理 - 请参阅 "获取方法类型信息" 部分 - 关于反射的一般教程.

This is dealt with on the Oracle tutorials website - see "Obtaining Method Type Information" part - of the general tutorial on reflection.

总而言之 - 在您致电后

In summary - after you call

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

你需要这样的东西:

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

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

and/or (depending whether your methods might use generics in their parameter types)

Type[] gpType = m.getGenericParameterTypes();

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

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

这篇关于如果参数类型未知,则通过变量调用带参数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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