@FunctionalInterface
public interface MethodInvocationExceptionHandler {
public Object handle(Method metodo, InvocationTargetException ex);
}
public class ManipuladorMetodo {
private Object instancia;
private Method metodo;
private Map<String, Object> params;
private MethodInvocationExceptionHandler exceptionHandler;
public ManipuladorMetodo(Object instancia, Method metodo, Map<String, Object> params) {
this.instancia = instancia;
this.metodo = metodo;
this.params = params;
}
public Object invoca() {
try {
List<Object> parametros = new ArrayList<>();
Stream.of(metodo.getParameters()).forEach(arg -> parametros.add(params.get(arg.getName())));
return metodo.invoke(instancia, parametros.toArray());
} catch (IllegalAccessException | IllegalArgumentException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (InvocationTargetException ex) {
return exceptionHandler.handle(metodo, ex);
}
}
public ManipuladorMetodo comTratamentoDeExcecao(MethodInvocationExceptionHandler exceptionHandler) {
this.exceptionHandler = exceptionHandler;
return this;
}
}
public class Alurator {
//...
public Object executa(String url) {
Request request = new Request(url);
String nomeControle = request.getNomeControle();
String nomeMetodo = request.getNomeMetodo();
Map<String, Object> params = request.getQueryParams();
Object retorno = new Reflexao()
.refleteClasse( pacoteBase + nomeControle )
.criaInstancia()
.getMetodo(nomeMetodo, params)
.comTratamentoDeExcecao((metodo, ex) -> {
System.out.println(ex.getCause().getMessage());
throw new RuntimeException(ex.getCause());
})
.invoca();
System.out.println(retorno);
return retorno;
}
}