1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package info.magnolia.objectfactory;
35
36 import org.apache.commons.beanutils.ConstructorUtils;
37
38 import java.lang.reflect.InvocationTargetException;
39 import java.util.Arrays;
40
41
42
43
44
45
46
47 public class DefaultClassFactory implements ClassFactory {
48
49 public <C> Class<C> forName(String className) throws ClassNotFoundException {
50 Class<C> loadedClass;
51 try {
52 loadedClass = (Class<C>) Class.forName(className);
53 } catch (ClassNotFoundException e) {
54 loadedClass = (Class<C>) Class.forName(className, true, Thread.currentThread().getContextClassLoader());
55 }
56 return loadedClass;
57
58 }
59
60 public <T> T newInstance(final Class<T> c, final Class<?>[] argTypes, final Object... params) {
61 if (argTypes.length != params.length) {
62 throw new IllegalStateException("Argument types and values do not match! " + Arrays.asList(argTypes) + " / " + Arrays.asList(params));
63 }
64
65 return newInstance(c, params, new Invoker<T>() {
66 public T invoke() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, InstantiationException {
67 return (T) ConstructorUtils.invokeConstructor(c, params, argTypes);
68 }
69 });
70 }
71
72 public <T> T newInstance(final Class<T> c, final Object... params) {
73 return newInstance(c, params, new Invoker<T>() {
74 public T invoke() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
75 return (T) ConstructorUtils.invokeConstructor(c, params);
76 }
77 });
78 }
79
80 private <T> T newInstance(Class<T> c, Object[] params, Invoker<T> invoker) {
81
82
83
84
85 try {
86 if (params == null || params.length == 0) {
87
88 return c.newInstance();
89 }
90
91
92
93 return invoker.invoke();
94
95 } catch (NoSuchMethodException e) {
96 throw new MgnlInstantiationException(e.getMessage(), e);
97 } catch (IllegalAccessException e) {
98 throw new MgnlInstantiationException(e.getMessage(), e);
99 } catch (InvocationTargetException e) {
100 throw new MgnlInstantiationException(e.getMessage(), e);
101 } catch (InstantiationException e) {
102 throw new MgnlInstantiationException(e.getMessage(), e);
103 }
104 }
105
106 private static interface Invoker<T> {
107 T invoke() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException;
108 }
109
110 }