1 package com.atlassian.plugins.rest.module;
2
3 import java.lang.reflect.InvocationHandler;
4 import java.lang.reflect.InvocationTargetException;
5 import java.lang.reflect.Method;
6
7 public class ContextClassLoaderSwitchingProxy implements InvocationHandler
8 {
9 private final Object delegate;
10 private final ClassLoader[] classLoaders;
11
12 public ContextClassLoaderSwitchingProxy(final Object delegate, final ClassLoader... classLoaders)
13 {
14 this.delegate = delegate;
15 this.classLoaders = classLoaders;
16 }
17
18 public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable
19 {
20 ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
21 ChainingClassLoader chainingClassLoader = new ChainingClassLoader(classLoaders);
22 try
23 {
24 try
25 {
26 Thread.currentThread().setContextClassLoader(chainingClassLoader);
27 return method.invoke(delegate, args);
28 }
29 catch (InvocationTargetException e)
30 {
31 throw e.getCause();
32 }
33 }
34 finally
35 {
36 Thread.currentThread().setContextClassLoader(oldClassLoader);
37 }
38
39 }
40
41 }