作者InitialShuk (Shuk)
站内java
标题[问题] 关於一个传入参数
时间Sat Dec 5 16:23:16 2009
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)
1F:→ InitialShuk:顺便假设一个状况好了,如果没有getparametertype 12/05 16:56
2F:→ InitialShuk:要如何输入...? 我把那个method.tostring是乱码? 冏 12/05 16:59
3F:→ sbrhsieh:这样子根本没有解决你的问题,因为你还是不懂... 12/05 17:26
4F:→ InitialShuk:说的也是orz 12/05 17:27
5F:推 sbrhsieh:如果你知道 a[0] 就是 main method,那求 runMethod 的值 12/05 17:30
6F:→ sbrhsieh:干嘛?就直接 a[0].invoke(...) 也是执行 main method. 12/05 17:32
7F:→ InitialShuk:我没发现 orz.... 12/05 17:34