View Javadoc
1   package com.atlassian.plugin.util;
2   
3   import java.lang.reflect.InvocationHandler;
4   import java.lang.reflect.InvocationTargetException;
5   import java.lang.reflect.Method;
6   
7   /**
8    * InvocationHandler for a dynamic proxy that ensures all methods are executed with the
9    * object class's class loader as the context class loader.
10   *
11   * @since 3.1.0
12   */
13  public class ContextClassLoaderSettingInvocationHandler implements InvocationHandler {
14      private final Object service;
15  
16      private final ClassLoader serviceClassLoader;
17  
18      public ContextClassLoaderSettingInvocationHandler(final Object service) {
19          this.service = service;
20          this.serviceClassLoader = service.getClass().getClassLoader();
21      }
22  
23      public Object invoke(final Object o, final Method method, final Object[] objects) throws Throwable {
24          ClassLoaderStack.push(serviceClassLoader);
25          try {
26              return method.invoke(service, objects);
27          } catch (final InvocationTargetException e) {
28              throw e.getTargetException();
29          } finally {
30              ClassLoaderStack.pop();
31          }
32      }
33  }