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