看看我的代码....
Class<?> c = Class.forName("PerformanceInvokeService");
Method m = c.getDeclaredMethod("monthlyTestCal", new Class[] {
String.class, Date.class });
Object ret = m.invoke("PerformanceInvokeService", new Object[] {
"some string", new Date() });
System.out.println(ret);
我执行它并抛出异常
java.lang.IllegalArgumentException: object is not an instance of declaring class
我想,因为我没有创建 c 的实例(比如...new PerformanceInvokeService()) 而且我不知道如何创建它
有人帮忙吗?
对不起我的英语...
谢谢
最佳答案
如果 PerformanceInvokeService
有一个可访问的默认构造函数,您可以使用以下方法创建一个新实例:
Object instance = c.newInstance();
然后您可以将其传递给方法调用:
Object ret = m.invoke(instance, new Object[] { "some string", new Date() });
如果没有可访问的默认构造函数,那么您将必须找到一个可以通过反射使用的构造函数。
关于java - 如何将类转换为实例对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9714093/