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  {
15      private final Object service;
16  
17      public ContextClassLoaderSettingInvocationHandler(final Object service)
18      {
19          this.service = service;
20      }
21  
22      public Object invoke(final Object o, final Method method, final Object[] objects) throws Throwable
23      {
24          ClassLoaderStack.push(service.getClass().getClassLoader());
25          try
26          {
27              return method.invoke(service, objects);
28          }
29          catch (final InvocationTargetException e)
30          {
31              throw e.getTargetException();
32          }
33          finally
34          {
35              ClassLoaderStack.pop();
36          }
37      }
38  }