Create an exception-safe class wrapper

I have an inherited class C1 that implements interface I, which may raise some exceptions.

I want to create a class C2 that also implements interface I, which is based on an instance of C1, but catches all the exceptions and does something useful about them.

Currently my implementation is as follows:

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

(Note: I could also make C2 a continuation of C1. It does not matter for the current question).

The interface contains many functions, so I have to write the same try ... catch block again and again.

Is there a way to reduce the amount of code duplication here?

+6
source share
1 answer

You can make a proxy server, it can be shared

 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(); } } 
+1
source

Source: https://habr.com/ru/post/944341/


All Articles