1
2
3
4
5
6
7
8
9
10 package net.sf.mmapps.commons.util;
11
12 import java.lang.reflect.Constructor;
13
14 public class ReflectionUtil {
15
16 private ReflectionUtil() {
17
18 }
19
20 public static Object createInstance(String className) throws Exception {
21 return createInstance(className, null);
22 }
23
24 public static Object createInstance(String className, Object[] arguments) throws Exception {
25 if (arguments != null && arguments.length > 0) {
26 Class[] classes = getClasses(arguments);
27 return createInstance(className, classes, arguments);
28 }
29 else {
30 return createInstance(className, null, arguments);
31 }
32 }
33
34 public static Object createInstance(String className, Class[] classes, Object[] arguments) throws Exception {
35 Class type = Class.forName(className);
36 if (type != null) {
37 if (classes != null && classes.length > 0) {
38 Constructor constr = null;
39 try {
40 constr = type.getConstructor(classes);
41 }
42 catch (Exception e) {
43 throw new Exception("class (" + type.getName()
44 + ") does not implement public constructor with arguments", e);
45 }
46 try {
47 return constr.newInstance(arguments);
48 }
49 catch (Throwable t) {
50 throw new Exception("failed to create new instance of " + className, t);
51 }
52 }
53 else {
54 try {
55 return type.newInstance();
56 }
57 catch (Throwable t) {
58 throw new Exception("failed to create new instance of " + className, t);
59 }
60 }
61 }
62 else {
63 throw new Exception("failed to find Class for " + className);
64 }
65 }
66
67 public static boolean hasConstructor(String className, Object[] arguments) throws ClassNotFoundException {
68 Class[] classes = getClasses(arguments);
69 return hasConstructor(className, classes);
70 }
71
72 public static boolean hasConstructor(String className, Class[] classes) throws ClassNotFoundException {
73 Class type = Class.forName(className);
74 if (type != null) {
75 try {
76 type.getConstructor(classes);
77 }
78 catch (Exception e) {
79 return false;
80 }
81 return true;
82 }
83 else {
84 return false;
85 }
86 }
87
88 public static Class[] getClasses(Object[] arguments) {
89 Class[] classes = null;
90 if (arguments != null && arguments.length > 0) {
91 classes = new Class[arguments.length];
92 for (int i = 0; i < arguments.length; i++) {
93 classes[i] = arguments[i].getClass();
94 }
95 }
96 return classes;
97 }
98 }