public class InvokeTester { public InvokeTester() { } String str; public InvokeTester(String str) { this.str = str; } public int add(int param1, int param2) { return param1 + param2; } public String echo(String msg) { return "echo: " + msg; } public String getStr() { return "one param ctor" + str; } public static void main(String[] args) throws Exception { //直接獲取類 //Class<?> classType = InvokeTester.class; //經過完整的類型路徑獲取類 Class<?> classType = Class.forName("com.top.utils.InvokeTester"); //使用newInstance建立對象 // Object invokeTester = classType.newInstance(); //使用默認構造函數獲取對象 Object invokeTester = classType.getConstructor(new Class[]{}).newInstance(new Object[]{}); //獲取InvokeTester類的add()方法 Method addMethod = classType.getMethod("add", new Class[]{int.class, int.class}); //調用invokeTester對象上的add()方法 Object result = addMethod.invoke(invokeTester, new Object[]{new Integer(100), new Integer(200)}); System.out.println((Integer) result); //獲取InvokeTester類的echo()方法 Method echoMethod = classType.getMethod("echo", new Class[]{String.class}); //調用invokeTester對象的echo()方法 result = echoMethod.invoke(invokeTester, new Object[]{"Hello"}); System.out.println((String) result); //建立有參構造函數的類對象 Object invokeTester1 = classType.getConstructor(new Class[]{String.class}).newInstance(new Object[]{new String("測試一個帶參數的構造調用")}); //獲取方法方式相同 Method getStrMethod = classType.getMethod("getStr"); Object str = getStrMethod.invoke(invokeTester1); System.out.println(str); } }