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 java.lang.reflect.InvocationTargetException;
37 import java.util.Arrays;
38
39 import org.apache.commons.beanutils.ConstructorUtils;
40
41
42
43
44 public class DefaultClassFactory implements ClassFactory {
45
46 @Override
47 public <C> Class<C> forName(String className) throws ClassNotFoundException {
48 Class<C> loadedClass;
49 try {
50 loadedClass = (Class<C>) Class.forName(className);
51 } catch (ClassNotFoundException e) {
52 loadedClass = (Class<C>) Class.forName(className, true, Thread.currentThread().getContextClassLoader());
53 }
54 return loadedClass;
55
56 }
57
58 @Override
59 public <T> T newInstance(final Class<T> c, final Class<?>[] argTypes, final Object... params) {
60 if (argTypes.length != params.length) {
61 throw new IllegalStateException("Argument types and values do not match! " + Arrays.asList(argTypes) + " / " + Arrays.asList(params));
62 }
63
64 return newInstance(c, params, new Invoker<T>() {
65 @Override
66 public T invoke() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, InstantiationException {
67 return ConstructorUtils.invokeConstructor(c, params, argTypes);
68 }
69 });
70 }
71
72 @Override
73 public <T> T newInstance(final Class<T> c, final Object... params) {
74 return newInstance(c, params, new Invoker<T>() {
75 @Override
76 public T invoke() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
77 return ConstructorUtils.invokeConstructor(c, params);
78 }
79 });
80 }
81
82 private <T> T newInstance(Class<T> c, Object[] params, Invoker<T> invoker) {
83
84
85
86
87 try {
88 if (params == null || params.length == 0) {
89
90 return c.newInstance();
91 }
92
93
94
95 return invoker.invoke();
96
97 } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
98 throw new MgnlInstantiationException(e.getMessage(), e);
99 }
100 }
101
102 private static interface Invoker<T> {
103 T invoke() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException;
104 }
105
106 }