01: /*
02: Mdarad-Toolobox is a collection of tools for Architected RAD
03: (Rapid Application Development) based on an MDA approach.
04: The toolbox contains frameworks and generators for many environments
05: (JAVA, J2EE, Hibernate, .NET, C++, etc.) which allow to generate
06: applications from a design Model
07: Copyright (C) 2004-2005 Elapse Technologies Inc.
08:
09: This library is free software; you can redistribute it and/or
10: modify it under the terms of the GNU General Public
11: License as published by the Free Software Foundation; either
12: version 2.1 of the License, or (at your option) any later version.
13:
14: This library is distributed in the hope that it will be useful,
15: but WITHOUT ANY WARRANTY; without even the implied warranty of
16: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17: General Public License for more details.
18:
19: You should have received a copy of the GNU General Public
20: License along with this library; if not, write to the Free Software
21: Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22: */
23: package org.mdarad.framework.util;
24:
25: import java.lang.reflect.Constructor;
26: import java.lang.reflect.InvocationTargetException;
27:
28: /**
29: * This class contains static methods used to make some
30: * operation on or with classes such as dyanamically instanciate
31: * a <code>Class</code> object.
32: * @author Philippe Brouillette
33: * @version 1.0
34: * @since 1.4
35: */
36: public class ClassUtils {
37:
38: /**
39: * Method that dynamically instanciates a class using the
40: * constructor with the argument types specified by the
41: * argument <code>construcotrArgTypes</code>. The values for
42: * the types are passed by <code>constructorArgs</code>.
43: * @param type the class to be instanciated
44: * @param constructorArgTypes the argument types of the constructor to use
45: * @param constructorArgs the values for the arguments of the constructor.
46: * @return an instance of the class
47: */
48: public static Object getInstance(Class type,
49: Class[] constructorArgTypes, Object[] constructorArgs)
50: throws ClassUtilsException {
51: if (type == null) {
52: throw new IllegalArgumentException(
53: "The type should never be null");
54: }
55: Object object = null;
56: try {
57: Constructor constructor = type
58: .getConstructor(constructorArgTypes);
59: object = constructor.newInstance(constructorArgs);
60: } catch (NoSuchMethodException nsme) {
61: throw new ClassUtilsException(
62: "Constructor could not be found", nsme);
63: } catch (InstantiationException ie) {
64: throw new ClassUtilsException(
65: "Instance could not be created", ie);
66: } catch (IllegalAccessException ie) {
67: throw new ClassUtilsException(
68: "Instance could not be created", ie);
69: } catch (InvocationTargetException ie) {
70: throw new ClassUtilsException(
71: "Instance could not be created", ie);
72: }
73: return object;
74: }
75: }
|