View Javadoc

1   /**
2    *  Copyright 2003-2006 Greg Luck
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   */
16  
17  package net.sf.ehcache.util;
18  
19  import net.sf.ehcache.CacheException;
20  
21  /**
22   * Keeps all classloading in ehcache consistent.
23   *
24   * @author Greg Luck
25   * @version $Id: ClassLoaderUtil.java 52 2006-04-24 14:50:03Z gregluck $
26   */
27  public final class ClassLoaderUtil {
28  
29      /**
30       * Utility class.
31       */
32      private ClassLoaderUtil() {
33          //noop
34      }
35  
36      /**
37       * Gets the <code>ClassLoader</code> that all classes in ehcache, and extensions, should use for classloading.
38       * All ClassLoading in ehcache should use this one. This is the only thing that seems to work for all of the
39       * class loading situations found in the wild.
40       * @return the thread context class loader.
41       */
42      public static ClassLoader getStandardClassLoader() {
43          return Thread.currentThread().getContextClassLoader();
44      }
45  
46      /**
47       * Creates a new class instance. Logs errors along the way. Classes are loaded using the
48       * ehcache standard classloader.
49       *
50       * @param className a fully qualified class name
51       * @return null if the instance cannot be loaded
52       */
53      public static Object createNewInstance(String className) throws CacheException {
54          Class clazz;
55          Object newInstance;
56          try {
57              clazz = Class.forName(className, true, getStandardClassLoader());
58              newInstance = clazz.newInstance();
59          } catch (ClassNotFoundException e) {
60              throw new CacheException("Unable to load class " + className + ". Initial cause was " + e.getMessage(), e);
61          } catch (IllegalAccessException e) {
62              throw new CacheException("Unable to load class " + className + ". Initial cause was " + e.getMessage(), e);
63          } catch (InstantiationException e) {
64              throw new CacheException("Unable to load class " + className + ". Initial cause was " + e.getMessage(), e);
65          }
66          return newInstance;
67      }
68  
69  
70  }