1 package net.secodo.jcircuitbreaker.task.experimental;
2
3 import java.lang.reflect.Method;
4
5 import net.secodo.jcircuitbreaker.task.Task;
6
7
8
9
10
11
12
13
14
15 public class MethodInvokingTask<R, T> implements Task<R> {
16 private final T object;
17 private final Object[] methodParams;
18 private final Method method;
19
20
21
22
23
24
25
26
27
28
29 public MethodInvokingTask(T object, String methodName, Class<R> methodReturnType, Object... methodParams)
30 throws NoSuchMethodException {
31 this.object = object;
32 this.methodParams = methodParams;
33
34 Class<?>[] methodParamTypes = new Class[methodParams.length];
35
36 for (int i = 0; i < methodParams.length; i++) {
37 methodParamTypes[i] = methodParams[i].getClass();
38 }
39
40 method = object.getClass().getDeclaredMethod(methodName, methodParamTypes);
41
42 final Class<?> returnType = method.getReturnType();
43
44 if (methodReturnType != returnType) {
45 throw new NoSuchMethodException(
46 "Given method return type: " + returnType + " does not match wanted return " +
47 "type: " + methodReturnType);
48 }
49
50 }
51
52
53 @Override
54 @SuppressWarnings("unchecked")
55 public R execute() throws Exception {
56 return (R) method.invoke(object, methodParams);
57 }
58 }