创建类的异常安全包装器



我有一个遗留类C1,实现接口I,可能会抛出一些异常。

我想创建一个类C2,也实现接口I,它基于C1的实例,但捕获所有异常并对它们做一些有用的事情。

目前我的实现是这样的:

class C2 implements I {
    C1 base;
    @Override void func1() {
      try {
         base.func1();
      } catch (Exception e) {
         doSomething(e);
      }
    }
    @Override void func2() {
      try {
         base.func2();
      } catch (Exception e) {
         doSomething(e);
      }
    }
    ...
}

(注意:我也可以让C2扩展C1。这对当前的问题不重要)。

这个接口包含了很多函数,所以我不得不写同样的try…一次又一次的Catch块

有没有办法减少这里的代码重复量?

你可以创建一个代理,它实际上可以是通用的

interface I1 {
    void test();
}
class C1 implements I1 {
    public void test() {
        System.out.println("test");
        throw new RuntimeException();
    }
}
class ExceptionHandler implements InvocationHandler {
    Object obj;
    ExceptionHandler(Object obj) {
        this.obj = obj;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            return method.invoke(obj, args);
        } catch (Exception e) {
            // need a workaround for primitive return types
            return null;
        }
    }
    static <T> T proxyFor(Object obj, Class<T> i) {
        return (T) Proxy.newProxyInstance(obj.getClass().getClassLoader(), new Class[] { i },
                new ExceptionHandler(obj));
    }
}
public class Test2 {
    public static void main(String[] args) throws Exception {
        I1 i1 = ExceptionHandler.proxyFor(new C1(), I1.class);
        i1.test();
    }
}

最新更新