1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.collections4.functors;
18
19 import java.lang.reflect.Constructor;
20 import java.lang.reflect.InvocationTargetException;
21 import java.util.Objects;
22
23 import org.apache.commons.collections4.Factory;
24 import org.apache.commons.collections4.FunctorException;
25
26
27
28
29
30
31
32
33
34
35
36
37
38 public class InstantiateFactory<T> implements Factory<T> {
39
40
41
42
43
44
45
46
47
48
49
50
51 public static <T> Factory<T> instantiateFactory(final Class<T> classToInstantiate,
52 final Class<?>[] paramTypes,
53 final Object[] args) {
54 Objects.requireNonNull(classToInstantiate, "classToInstantiate");
55 if (paramTypes == null && args != null
56 || paramTypes != null && args == null
57 || paramTypes != null && args != null && paramTypes.length != args.length) {
58 throw new IllegalArgumentException("Parameter types must match the arguments");
59 }
60
61 if (paramTypes == null || paramTypes.length == 0) {
62 return new InstantiateFactory<>(classToInstantiate);
63 }
64 return new InstantiateFactory<>(classToInstantiate, paramTypes, args);
65 }
66
67 private final Class<T> iClassToInstantiate;
68
69 private final Class<?>[] iParamTypes;
70
71 private final Object[] iArgs;
72
73
74 private transient Constructor<T> iConstructor;
75
76
77
78
79
80
81
82 public InstantiateFactory(final Class<T> classToInstantiate) {
83 iClassToInstantiate = classToInstantiate;
84 iParamTypes = null;
85 iArgs = null;
86 findConstructor();
87 }
88
89
90
91
92
93
94
95
96
97 public InstantiateFactory(final Class<T> classToInstantiate, final Class<?>[] paramTypes, final Object[] args) {
98 iClassToInstantiate = classToInstantiate;
99 iParamTypes = paramTypes.clone();
100 iArgs = args.clone();
101 findConstructor();
102 }
103
104
105
106
107
108
109 @Override
110 public T create() {
111
112 if (iConstructor == null) {
113 findConstructor();
114 }
115
116 try {
117 return iConstructor.newInstance(iArgs);
118 } catch (final InstantiationException ex) {
119 throw new FunctorException("InstantiateFactory: InstantiationException", ex);
120 } catch (final IllegalAccessException ex) {
121 throw new FunctorException("InstantiateFactory: Constructor must be public", ex);
122 } catch (final InvocationTargetException ex) {
123 throw new FunctorException("InstantiateFactory: Constructor threw an exception", ex);
124 }
125 }
126
127
128
129
130 private void findConstructor() {
131 try {
132 iConstructor = iClassToInstantiate.getConstructor(iParamTypes);
133 } catch (final NoSuchMethodException ex) {
134 throw new IllegalArgumentException("InstantiateFactory: The constructor must exist and be public ");
135 }
136 }
137
138 }