forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountingInvocationHandler.java
More file actions
42 lines (32 loc) · 1.39 KB
/
Copy pathCountingInvocationHandler.java
File metadata and controls
42 lines (32 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package modern.challenge;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
public class CountingInvocationHandler implements InvocationHandler {
private final Map<String, Integer> counter = new HashMap<>();
private final Object targetObject;
public CountingInvocationHandler(Object targetObject) {
this.targetObject = targetObject;
for (Method method : targetObject.getClass().getDeclaredMethods()) {
this.counter.put(method.getName() + Arrays.toString(method.getParameterTypes()), 0);
}
}
public Map<String, Integer> countOf(String methodName) {
Map<String, Integer> result = counter.entrySet().stream()
.filter(e -> e.getKey().startsWith(methodName + "["))
.filter(e -> e.getValue() != 0)
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
return result;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object resultOfInvocation = method.invoke(targetObject, args);
counter.computeIfPresent(method.getName()
+ Arrays.toString(method.getParameterTypes()), (k, v) -> ++v);
return resultOfInvocation;
}
}