簡體   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