通过调用与参数匹配的构造函数来创建obj类的对象。
/** from N o w J a v a . c o m - 时代Java**/ /** * Copyright (c) 2011 eXtensible Catalog Organization * * This program is free software; you can redistribute it and/or modify it * under the terms of the MIT/X11 license. The text of the license can be * found at http://www.opensource.org/licenses/mit-license.php. */ import org.apache.log4j.Logger; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; public class Main{ /** * Create an object of the objClass by calling the constructor that matches the parameters. * @param objClass * @param parameters * @return */ public static Object createObject(Class objClass, Object... parameters) throws ToolkitException { Object obj; try { Class[] parmTypes; if (parameters != null) { /** 来自 nowjava - 时代Java**/ parmTypes = new Class[parameters.length]; for (int index = 0; index < parameters.length; ++index) { parmTypes[index] = parameters[index].getClass(); // Strip quote marks from around strings // Note: this would change the type of objects that are sub-classes of String into String, // but as String is a final class there can't actually be any sub-types of String, // so this is safe to do. if (parameters[index] instanceof String) { String temp = (String) parameters[index]; if (temp.startsWith("\"") && temp.endsWith("\"")) { parameters[index] = temp.substring(1, temp.length() - 1); } } } } else { parmTypes = new Class[0]; } Constructor ctor = objClass.getConstructor(parmTypes); obj = ctor.newInstance(parameters); } catch (InstantiationException e) { throw new ToolkitException( "Exception constructing an instance of " + objClass, e); } catch (IllegalAccessException e) { throw new ToolkitException( "Exception constructing an instance of " + objC