项目中有这个写法,感觉很方便。主要的场景是为callback设置executor。
使用场景
假如我们有一个方法,需要将执行结果回调回去。
// 接口回调
public interface CallBack {
void onResult(String result);
}
public void doSomething(CallBack callBack) {
String result = "zsm";
if (callBack != null) {
callBack.onResult(result);
}
}
public static void main(String[] args) {
new Main().doSomething(result -> print("result:" + result));
}
public static void print(String msg) {
String name = Thread.currentThread().getName();
System.out.println(name + ":" + msg);
}
此时回调执行线程为main,假如我们要求在其他线程执行,可以使用代理改写下。
具体实现
public class Proxy {
private Executor executor;
private List<Class> classList;
private Proxy(Class clazz) {
classList = new ArrayList<>();
classList.add(clazz);
}
public static Proxy of(Class clazz) {
return new Proxy(clazz);
}
public <T> T by(T t) {
ClassLoader classLoader = t.getClass().getClassLoader();
return (T) java.lang.reflect.Proxy.newProxyInstance(classLoader, classList.toArray(new Class[0]), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (executor != null) {
if (void.class != method.getReturnType()) {
throw new IllegalArgumentException("return type must be void");
}
executor.execute(() -> {
try {
method.invoke(t, args);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
});
return null;
} else {
return method.invoke(t, args);
}
}
});
}
public Proxy setExecutor(Executor executor) {
this.executor = executor;
return this;
}
}
public void doSomething2(CallBack callBack) {
callBack = Proxy.of(CallBack.class)
.setExecutor(command -> new Thread(command).start())
.by(callBack);
String result = "zsm";
if (callBack != null) {
callBack.onResult(result);
}
}
以上实现callback执行在指定的线程中。
此外还可以拓展:
- 异常处理
- 方法耗时检测
- 方法执行超时限制
- 方法执行埋点等
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!