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 private final Object delegate;
9 private final ClassLoader[] classLoaders;
10
11 public ContextClassLoaderSwitchingProxy(final Object delegate, final ClassLoader... classLoaders) {
12 this.delegate = delegate;
13 this.classLoaders = classLoaders;
14 }
15
16 public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
17 ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
18 ChainingClassLoader chainingClassLoader = new ChainingClassLoader(classLoaders);
19 try {
20 try {
21 Thread.currentThread().setContextClassLoader(chainingClassLoader);
22 return method.invoke(delegate, args);
23 } catch (InvocationTargetException e) {
24 throw e.getCause();
25 }
26 } finally {
27 Thread.currentThread().setContextClassLoader(oldClassLoader);
28 }
29
30 }
31
32 }