import java.lang.reflect.Method; import java.util.Arrays; /** * @Author: hoobey * @Description: * @Date: Created in 9:35 2018/1/6 * @Modified By: * method.invoke(方法底層所屬對象/null,new Object[]{實際參數}) */ public class ClientInvoke { /*反射調方法時不管是靜態/非靜態,固定/可變參數,都有Object對象數組對參數進行包裝 * */ public static void main(String[] args) throws Exception { Class<User> clas = User.class; Method m = clas.getMethod("method", String[].class); m.invoke(null, new Object[]{new String[]{"aa", "bb", "cc"}});//靜態方法可省略對象,直接用null替代,或用clas m = clas.getDeclaredMethod("method", int[].class);//非public方法要用declared獲取 m.setAccessible(true);//非public方法須要設置爲可訪問 m.invoke(clas.newInstance(), new int[]{1, 2, 3, 4, 3, 2, 1});//非靜態方法須要提供底層的類對象 } } class User { public static void method(String... strings) { System.out.println(Arrays.toString(strings)); } private void method(int... ints) { System.out.println(Arrays.toString(ints)); } }