MultipleLoaderClassResolver.java

  1. package com.gh.mygreen.xlsmapper.xml;

  2. import java.util.Collection;
  3. import java.util.HashSet;
  4. import java.util.Iterator;
  5. import java.util.Map;

  6. import ognl.ClassResolver;

  7. /**
  8.  * ClassResolver loading from multiple ClassLoader in Ognl.
  9.  *
  10.  * @author Mitsuyoshi Hasegawa
  11.  */
  12. public class MultipleLoaderClassResolver implements ClassResolver {

  13.     /**
  14.      * Loads class from multiple ClassLoader.
  15.      *
  16.      * If this method can not load target class,
  17.      * it tries to add package java.lang(default package)
  18.      *  and load target class.
  19.      * Still, if it can not the class, throws ClassNotFoundException.
  20.      * (behavior is put together on DefaultClassResolver.)
  21.      *
  22.      * @param className class name --  that wants to load it.
  23.      * @param loaderMap map -- that has VALUES ClassLoader (KEYS are arbitary).
  24.      * @return loaded class from ClassLoader defined loaderMap.
  25.      */
  26.     @SuppressWarnings({"unchecked", "rawtypes"})
  27.     public Class classForName(String className, Map loaderMap) throws ClassNotFoundException {
  28.         Collection<ClassLoader> loaders = null;
  29.         // add context-classloader
  30.         loaders = new HashSet<ClassLoader>();
  31.         loaders.add(Thread.currentThread().getContextClassLoader());
  32.         if (loaderMap != null && !loaderMap.isEmpty()) {
  33.             loaders.addAll(loaderMap.values());
  34.         }
  35.         Class clazz = null;
  36.         ClassNotFoundException lastCause = null;
  37.         for (Iterator<ClassLoader> it = loaders.iterator(); it.hasNext();) {
  38.             ClassLoader loader = it.next();
  39.             try {
  40.                 clazz = loader.loadClass(className);
  41.                 return clazz;
  42.             } catch (ClassNotFoundException fqcnException) {
  43.                 lastCause = fqcnException;
  44.                 try {
  45.                     if (className.indexOf('.') == -1) {
  46.                         clazz = loader.loadClass("java.lang." + className);
  47.                         return clazz;
  48.                     }
  49.                 } catch (ClassNotFoundException defaultClassException) {
  50.                     lastCause = defaultClassException;
  51.                     // try next loader.
  52.                 }
  53.             }
  54.         }
  55.        
  56.         if(lastCause != null) {
  57.             // can't load class at end.
  58.             throw lastCause;
  59.         }
  60.        
  61.         return clazz;
  62.     }
  63. }