001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.kernel.bean;
016    
017    import java.lang.Object;
018    import java.lang.reflect.InvocationHandler;
019    import java.lang.reflect.InvocationTargetException;
020    import java.lang.reflect.Method;
021    
022    /**
023     * @author Brian Wing Shun Chan
024     */
025    public class ClassLoaderBeanHandler implements InvocationHandler {
026    
027            public ClassLoaderBeanHandler(Object bean, ClassLoader classLoader) {
028                    _bean = bean;
029                    _classLoader = classLoader;
030            }
031    
032            public Object getBean() {
033                    return _bean;
034            }
035    
036            public ClassLoader getClassLoader() {
037                    return _classLoader;
038            }
039    
040            public Object invoke(Object proxy, Method method, Object[] args)
041                    throws Throwable {
042    
043                    Thread currentThread = Thread.currentThread();
044    
045                    ClassLoader contextClassLoader = currentThread.getContextClassLoader();
046    
047                    try {
048                            if ((_classLoader != null) &&
049                                    (contextClassLoader != _classLoader)) {
050    
051                                    currentThread.setContextClassLoader(_classLoader);
052                            }
053    
054                            return method.invoke(_bean, args);
055                    }
056                    catch (InvocationTargetException ite) {
057                            throw ite.getTargetException();
058                    }
059                    finally {
060                            if ((_classLoader != null) &&
061                                    (contextClassLoader != _classLoader)) {
062    
063                                    currentThread.setContextClassLoader(contextClassLoader);
064                            }
065                    }
066            }
067    
068            private Object _bean;
069            private ClassLoader _classLoader;
070    
071    }