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