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.InvocationTargetException;
20 import java.lang.reflect.Method;
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 InvokerTransformer<I, O> implements Transformer<I, O> {
37
38
39 private final String iMethodName;
40
41 private final Class<?>[] iParamTypes;
42
43 private final Object[] iArgs;
44
45
46
47
48
49
50
51
52
53
54
55 public static <I, O> Transformer<I, O> invokerTransformer(final String methodName) {
56 if (methodName == null) {
57 throw new NullPointerException("The method to invoke must not be null");
58 }
59 return new InvokerTransformer<>(methodName);
60 }
61
62
63
64
65
66
67
68
69
70
71
72
73
74 public static <I, O> Transformer<I, O> invokerTransformer(final String methodName, final Class<?>[] paramTypes,
75 final Object[] args) {
76 if (methodName == null) {
77 throw new NullPointerException("The method to invoke must not be null");
78 }
79 if (((paramTypes == null) && (args != null))
80 || ((paramTypes != null) && (args == null))
81 || ((paramTypes != null) && (args != null) && (paramTypes.length != args.length))) {
82 throw new IllegalArgumentException("The parameter types must match the arguments");
83 }
84 if (paramTypes == null || paramTypes.length == 0) {
85 return new InvokerTransformer<>(methodName);
86 }
87 return new InvokerTransformer<>(methodName, paramTypes, args);
88 }
89
90
91
92
93
94
95 private InvokerTransformer(final String methodName) {
96 super();
97 iMethodName = methodName;
98 iParamTypes = null;
99 iArgs = null;
100 }
101
102
103
104
105
106
107
108
109
110
111
112 public InvokerTransformer(final String methodName, final Class<?>[] paramTypes, final Object[] args) {
113 super();
114 iMethodName = methodName;
115 iParamTypes = paramTypes != null ? paramTypes.clone() : null;
116 iArgs = args != null ? args.clone() : null;
117 }
118
119
120
121
122
123
124
125 @Override
126 @SuppressWarnings("unchecked")
127 public O transform(final Object input) {
128 if (input == null) {
129 return null;
130 }
131 try {
132 final Class<?> cls = input.getClass();
133 final Method method = cls.getMethod(iMethodName, iParamTypes);
134 return (O) method.invoke(input, iArgs);
135 } catch (final NoSuchMethodException ex) {
136 throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" +
137 input.getClass() + "' does not exist");
138 } catch (final IllegalAccessException ex) {
139 throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" +
140 input.getClass() + "' cannot be accessed");
141 } catch (final InvocationTargetException ex) {
142 throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" +
143 input.getClass() + "' threw an exception", ex);
144 }
145 }
146
147 }