com.yixan.tools.common.sync.SyncInvoker Maven / Gradle / Ivy
package com.yixan.tools.common.sync;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import com.yixan.tools.common.util.ReflectUtil;
/**
* 异步执行方法, 带结果回调
* Callback<String> callback = new Callback.Log<>();
* Args args = new AnyArgs(arg1, arg2);
* new SyncInvoker<XxxService, String>(xxxService, "methood", args, callback).start();
*
* @author zhaohuihua
* @version V1.0 2017年5月26日
*/
public class SyncInvoker extends Thread {
protected T target;
protected String method;
protected Args args;
protected Callback super R> callback;
public SyncInvoker(T target, String method, Args args, Callback super R> callback) {
this.target = target;
this.method = method;
this.args = args;
this.callback = callback;
}
public void run() {
Class>[] types = args.types();
Object[] values = args.values();
try {
Method method = ReflectUtil.findMethod(target.getClass(), this.method, types);
Object result = method.invoke(target, values);
if (callback != null) {
@SuppressWarnings("unchecked")
R r = (R) result;
callback.done(r);
}
} catch (Throwable e) {
if (e instanceof InvocationTargetException) { // method.invoke抛出未捕获的异常由该异常包装
e = e.getCause();
}
if (callback != null) {
callback.fail(target, method, args, e);
}
}
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy