简体   繁体   中英

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

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

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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