这是我正在处理的代码,它在运行时使用为构造函数提供的参数实例化和创建对象。
private static void createInstancesFromSpecfication() {
String[] specifierFileNames = resourceMap.get("instances");
if (null == specifierFileNames)
return;
List<SpecifierObjects> instances = new ArrayList<SpecifierObjects>();
for (int i = 0; i < specifierFileNames.length; i++) {
try {
instances.addAll(XMLFileUtility.readXML(specifierFileNames[i],
new ClassInstantiationHandler()));
} catch (ResourceNotAvailableException | DocumentException
| ResourceDataFailureException e) {
e.printStackTrace();
}
}
for (Iterator<SpecifierObjects> iterator = instances.iterator(); iterator
.hasNext();) {
InstanceSpecifierObject instanceSpecifierObject = (InstanceSpecifierObject) iterator
.next();
try {
Class<?> cast = Class.forName(instanceSpecifierObject
.getInterfaceName());
Class<?> clazz = Class.forName(instanceSpecifierObject
.getClassName());
Constructor<?> constructor = clazz
.getConstructor(String[].class);
Object obj = constructor.newInstance(instanceSpecifierObject
.getFilesName());
objects.put(instanceSpecifierObject.getObjectName(),
cast.cast(obj));
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | IllegalArgumentException
| InvocationTargetException | NoSuchMethodException
| SecurityException e) {
e.printStackTrace();
}
}
}
例外日志是:
instances=/home/user/workspace/CoreLibs/src/instanceSpecification.xml
/home/user/workspace/CoreLibs/src/instanceSpecification.xml
java.lang.IllegalArgumentException: wrong number of arguments
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.framew.confinit.ApplicationResource.createInstancesFromSpecfication(ApplicationResource.java:87)
at com.framew.confinit.ApplicationResource.importResource(ApplicationResource.java:58)
at com.framew.confinit.ApplicationResource.main(ApplicationResource.java:40)
我在这句话中得到了例外:
Object obj = constructor.newInstance(instanceSpecifierObject.getFilesName());
instanceSpecifierObject.getFilesNames()将一个文件名数组重新编译为String对象(如String [])。我也尝试将它们作为Object []传递,但是得到了同样的例外。
感谢任何帮助。在此先感谢。
答案 0 :(得分:0)