[問題] 關於一個傳入參數 (自解 orz

看板java作者 (Shuk)時間16年前 (2009/12/05 16:23), 編輯推噓1(106)
留言7則, 2人參與, 最新討論串1/2 (看更多)
public Method getMethod(String name,Class<?>... parameterTypes) ^^^^^^^^^^^^^^^^^^^^^^^^^^ 說明: The parameterTypes parameter is an array of Class objects that identify the method's formal parameter types, in declared order. If parameterTypes is null, it is treated as if it were an empty array. 當name這個method沒有傳入參數時可以不用輸入 使用此getMethod得到需要的method 但是如果有傳入參數呢? ex:int number,String args[]...... 我該怎麼輸入? -------------------------code---------------------- URLClassLoader loader = new URLClassLoader( new URL[]{new URL("http://127.0.0.1:8080/")},null); Class<?> c = loader.loadClass("Helloworld"); Method a[]=c.getDeclaredMethods(); //a[0].getname()=main,a[1].getname()=t Method runMethod = c.getMethod("t"); runMethod.invoke(c.newInstance());//成功印出hello Method runMethod = c.getMethod("main",a[0].getParameterTypes()); runMethod.invoke(c.newInstance(),args[]); //method如果有回傳值 此行等於回傳值 ps:Helloworld.class 包含 main(String[] args),t()兩個method 各自都是印出hello ------------------------- 自解: method object.getParameterTypes() runMethod.invoke(obj,args......); -- -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.115.222.4 ※ 編輯: InitialShuk 來自: 140.115.222.4 (12/05 16:51)

12/05 16:56, , 1F
順便假設一個狀況好了,如果沒有getparametertype
12/05 16:56, 1F

12/05 16:59, , 2F
要如何輸入...? 我把那個method.tostring是亂碼? 冏
12/05 16:59, 2F

12/05 17:26, , 3F
這樣子根本沒有解決你的問題,因為你還是不懂...
12/05 17:26, 3F

12/05 17:27, , 4F
說的也是orz
12/05 17:27, 4F

12/05 17:30, , 5F
如果你知道 a[0] 就是 main method,那求 runMethod 的值
12/05 17:30, 5F

12/05 17:32, , 6F
幹嘛?就直接 a[0].invoke(...) 也是執行 main method.
12/05 17:32, 6F

12/05 17:34, , 7F
我沒發現 orz....
12/05 17:34, 7F
文章代碼(AID): #1B6XXtgZ (java)
文章代碼(AID): #1B6XXtgZ (java)