如何避免在包装类中重复复杂的异常处理代码?
作者:互联网
我有这个包装对象的类:
public class MyWrapper implements MyInterface {
private MyInterface wrappedObj;
public MyWrapper(MyInterface obj) {
this.wrappedObj = obj;
}
@Override
public String ping(String s) {
return wrappedObj.ping(s);
}
@Override
public String doSomething(int i, String s) {
return wrappedObj.doSomething(i, s);
}
// many more methods ...
}
现在我想在wrappedObj调用周围添加复杂的异常处理.
所有方法都是一样的.
如何避免反复重复相同的异常处理代码?
解决方法:
如果您的异常处理是完全通用的,您可以将包装器实现为InvocationHandler:
public class ExceptionHandler implements java.lang.reflect.InvocationHandler {
public ExceptionHandler(Object impl) {
impl_ = impl;
}
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
return method.invoke(impl_, args);
}
catch (Exception e) {
// do exception handling magic and return something useful
return ...;
}
}
private Object impl_;
}
然后将其包装在实例中,如下所示:
MyInterface instance = ...
MyInterface wrapper = (MyInterface)java.lang.reflect.Proxy.newProxyInstance(
instance.getClass().getClassLoader(),
new Class[] { MyInterface.class },
new ExceptionHandler(instance));
wrapper.ping("hello");
标签:java,exception-handling,lambda,code-reuse 来源: https://codeday.me/bug/20190710/1427844.html