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
22 import org.apache.commons.collections4.FunctorException;
23 import org.apache.commons.collections4.Transformer;
24
25
26
27
28
29
30
31
32
33
34
35
36 public class InstantiateTransformer<T> implements Transformer<Class<? extends T>, T> {
37
38
39 @SuppressWarnings("rawtypes")
40 private static final Transformer NO_ARG_INSTANCE = new InstantiateTransformer<>();
41
42
43
44
45
46
47
48 public static <T> Transformer<Class<? extends T>, T> instantiateTransformer() {
49 return NO_ARG_INSTANCE;
50 }
51
52
53
54
55
56
57
58
59
60 public static <T> Transformer<Class<? extends T>, T> instantiateTransformer(final Class<?>[] paramTypes,
61 final Object[] args) {
62 if (paramTypes == null && args != null
63 || paramTypes != null && args == null
64 || paramTypes != null && args != null && paramTypes.length != args.length) {
65 throw new IllegalArgumentException("Parameter types must match the arguments");
66 }
67
68 if (paramTypes == null || paramTypes.length == 0) {
69 return new InstantiateTransformer<>();
70 }
71 return new InstantiateTransformer<>(paramTypes, args);
72 }
73
74
75 private final Class<?>[] iParamTypes;
76
77
78 private final Object[] iArgs;
79
80
81
82
83 private InstantiateTransformer() {
84 iParamTypes = null;
85 iArgs = null;
86 }
87
88
89
90
91
92
93
94
95
96
97 public InstantiateTransformer(final Class<?>[] paramTypes, final Object[] args) {
98 iParamTypes = paramTypes != null ? paramTypes.clone() : null;
99 iArgs = args != null ? args.clone() : null;
100 }
101
102
103
104
105
106
107
108 @Override
109 public T transform(final Class<? extends T> input) {
110 try {
111 if (input == null) {
112 throw new FunctorException(
113 "InstantiateTransformer: Input object was not an instanceof Class, it was a null object");
114 }
115 final Constructor<? extends T> con = input.getConstructor(iParamTypes);
116 return con.newInstance(iArgs);
117 } catch (final NoSuchMethodException ex) {
118 throw new FunctorException("InstantiateTransformer: The constructor must exist and be public ");
119 } catch (final InstantiationException ex) {
120 throw new FunctorException("InstantiateTransformer: InstantiationException", ex);
121 } catch (final IllegalAccessException ex) {
122 throw new FunctorException("InstantiateTransformer: Constructor must be public", ex);
123 } catch (final InvocationTargetException ex) {
124 throw new FunctorException("InstantiateTransformer: Constructor threw an exception", ex);
125 }
126 }
127
128 }