View Javadoc
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    * Explicitly encapsulates and object and method of the object which should be executed by <i>circuit breaker</i>.
10   * This class is experimental - it may change or be removed in future releases.
11   * 
12   * @param <R> return type of the class
13   * @param <T> the type/class of the object which contains the method that should be executed 
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     * Constructs new Task which invokes method with given name and method arguments on given object.
22     *
23     * @param object the object which contains the method with given name
24     * @param methodName the name of the method which should be executed
25     * @param methodReturnType class representing the return value of the method.
26     * @param methodParams the arguments which should be passed to the method
27     * @throws NoSuchMethodException if such method can not be found
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  }