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 public class InstantiateFactory<T> implements Factory<T> {
38
39
40
41
42
43
44
45
46
47
48
49
50 public static <T> Factory<T> instantiateFactory(final Class<T> classToInstantiate,
51 final Class<?>[] paramTypes,
52 final Object[] args) {
53 Objects.requireNonNull(classToInstantiate, "classToInstantiate");
54 if (paramTypes == null && args != null
55 || paramTypes != null && args == null
56 || paramTypes != null && args != null && paramTypes.length != args.length) {
57 throw new IllegalArgumentException("Parameter types must match the arguments");
58 }
59
60 if (paramTypes == null || paramTypes.length == 0) {
61 return new InstantiateFactory<>(classToInstantiate);
62 }
63 return new InstantiateFactory<>(classToInstantiate, paramTypes, args);
64 }
65
66 private final Class<T> iClassToInstantiate;
67
68 private final Class<?>[] iParamTypes;
69
70 private final Object[] iArgs;
71
72
73 private transient Constructor<T> iConstructor;
74
75
76
77
78
79
80
81 public InstantiateFactory(final Class<T> classToInstantiate) {
82 iClassToInstantiate = classToInstantiate;
83 iParamTypes = null;
84 iArgs = null;
85 findConstructor();
86 }
87
88
89
90
91
92
93
94
95
96 public InstantiateFactory(final Class<T> classToInstantiate, final Class<?>[] paramTypes, final Object[] args) {
97 iClassToInstantiate = classToInstantiate;
98 iParamTypes = paramTypes.clone();
99 iArgs = args.clone();
100 findConstructor();
101 }
102
103
104
105
106
107
108 @Override
109 public T create() {
110
111 if (iConstructor == null) {
112 findConstructor();
113 }
114
115 try {
116 return iConstructor.newInstance(iArgs);
117 } catch (final InstantiationException ex) {
118 throw new FunctorException("InstantiateFactory: InstantiationException", ex);
119 } catch (final IllegalAccessException ex) {
120 throw new FunctorException("InstantiateFactory: Constructor must be public", ex);
121 } catch (final InvocationTargetException ex) {
122 throw new FunctorException("InstantiateFactory: Constructor threw an exception", ex);
123 }
124 }
125
126
127
128
129 private void findConstructor() {
130 try {
131 iConstructor = iClassToInstantiate.getConstructor(iParamTypes);
132 } catch (final NoSuchMethodException ex) {
133 throw new IllegalArgumentException("InstantiateFactory: The constructor must exist and be public ");
134 }
135 }
136
137 }