How to avoid repeating complex exception handling code in wrapper classes?

I have this wrapper object class:

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 ...
}

Now I want to add complex exception handling around the wrappedobj call

All methods are the same

How to avoid repeating the same exception handling code repeatedly?

Solution

If your exception handling is completely generic, you can implement the wrapper as 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_;
}

It is then packaged in an example as follows:

MyInterface instance = ...
MyInterface wrapper = (MyInterface)java.lang.reflect.Proxy.newProxyInstance(
   instance.getClass().getClassLoader(),new Class[] { MyInterface.class },new ExceptionHandler(instance));

wrapper.ping("hello");
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>