Eclipse 報錯 The method getConstructor(Class[]) ... not applicable for the arguments (Class),實為 JDK 版本差異誤導。實際 getConstructor(Class>... parameterTypes) 是可變參數,直接傳 StringBuffer.class 即可,無需包裝數組。
// 單參構造器
Class> cl = Class.forName("java.lang.String");
Constructor> con = cl.getConstructor(StringBuffer.class); // 可變參數
String str = (String) con.newInstance(new StringBuffer("123"));
// 多參構造器:Person(String name, int age)
Class> pClz = Class.forName("com.example.Person");
Constructor> pCon = pClz.getConstructor(String.class, int.class); // 依次傳參數類型
Person person = (Person) pCon.newInstance("Jerome", 24); // 依次傳實參
getConstructor / newInstance 均為可變參數,按參數聲明順序依次傳遞即可。int.class、double.class 等 Class<?> 對象。NoSuchMethodException、InvocationTargetException、InstantiationException、IllegalAccessException。反射實例化屬於運行時行為,編譯期無法檢查參數匹配。建議封裝工具類統一異常處理與日誌,生產環境優先使用構造器直接調用或依賴注入框架。