Java中的Method.invoke方法参数解析
Java中的Method.invoke方法参数解析,可以根据传的参数类型,选择对应类型参数的方法进行执行方法,如下案例:
package demo; import java.lang.reflect.Method; public class Test2 { public void print(int ... ints) { for (int i = 0; i < ints.length; i++) { System.out.println(ints[i]); } } public void print(String ... Strings) { for (int i = 0; i < Strings.length; i++) { System.out.println(Strings[i]); } } public void print(char ... chars) { for (int i = 0; i < chars.length; i++) { System.out.println(chars[i]); } } public static void main(String[] args) { Class<?> c = Test2.class; try { Method m = c.getMethod("print", int[].class); m.invoke(c.newInstance(), new int[] {1,2,3,4,5}); System.out.println(); Method m1 = c.getMethod("print", String[].class); m1.invoke(c.newInstance(), new Object[] {new String[] {"aa","bb","cc"}}); System.out.println(); Method m2 = c.getMethod("print", char[].class); m2.invoke(c.newInstance(), new Object[] {new char[] {'a','b','c'}}); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }