package dk.thoerup.circuitbreaker.invocations; /* a annotation based invocation if it infeasible or you just don't like to implement yet another interface * * class MyInvocation { * @CircuitBreakerMethod * public void doSomething() {} * } * * ..... snip...... * * MyInvocation my = new MyInvocation(); * AnnotatedInvocation invok = new AnnotatedInvocation(my); * Object out = CircuitBreakerManager.getManager().getCircuitBreaker("mycb").invoke(invok); * */ import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import dk.thoerup.circuitbreaker.CircuitInvocation; public class AnnotatedInvocation implements CircuitInvocation { public static class CBAnnotationException extends Exception { public CBAnnotationException() { super("No method found annotated with @CircuitBreakerMethod"); } private static final long serialVersionUID = 1L; } private Object obj; public AnnotatedInvocation(Object obj) { this.obj = obj; } @SuppressWarnings("unchecked") public T proceed() throws Exception { Method methods[] = obj.getClass().getMethods(); for(Method current : methods) { Annotation anno = current.getAnnotation(CircuitBreakerMethod.class); if (anno != null ) { try { return (T) current.invoke(obj, (Object[])null); //invoke the first method annotated } catch (InvocationTargetException e) { throw (Exception) e.getCause(); //unwrap any exception from InvocationTargetException } } } throw new CBAnnotationException(); //if no method was found } }