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