1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.commons.jcs.jcache.proxy;
20
21 import java.lang.reflect.Constructor;
22 import java.lang.reflect.InvocationHandler;
23 import java.lang.reflect.InvocationTargetException;
24 import java.lang.reflect.Method;
25 import java.lang.reflect.Proxy;
26
27 public class ExceptionWrapperHandler<T> implements InvocationHandler
28 {
29 private final T delegate;
30 private final Constructor<? extends RuntimeException> wrapper;
31
32 public ExceptionWrapperHandler(final T delegate, final Class<? extends RuntimeException> exceptionType)
33 {
34 this.delegate = delegate;
35 try
36 {
37 this.wrapper = exceptionType.getConstructor(Throwable.class);
38 }
39 catch (final NoSuchMethodException e)
40 {
41 throw new IllegalStateException(e);
42 }
43 }
44
45 @Override
46 public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable
47 {
48 try
49 {
50 return method.invoke(delegate, args);
51 }
52 catch (final InvocationTargetException ite)
53 {
54 final Throwable e = ite.getCause();
55 if (RuntimeException.class.isInstance(e))
56 {
57 final RuntimeException re;
58 try
59 {
60 re = wrapper.newInstance(e);
61 }
62 catch (final Exception e1)
63 {
64 throw new IllegalArgumentException(e1);
65 }
66 throw re;
67 }
68 throw e;
69 }
70 }
71
72 public static <T> T newProxy(final ClassLoader loader, final T delegate, final Class<? extends RuntimeException> exceptionType,
73 final Class<T> apis)
74 {
75 return (T) Proxy.newProxyInstance(loader, new Class<?>[] { apis }, new ExceptionWrapperHandler<T>(delegate, exceptionType));
76 }
77 }