Java Class Load classForName(String className)

Here you can find the source of classForName(String className)

Description

Tries to load a class with more classloaders.

License

Artistic License

Parameter

Parameter Description
className class name

Exception

Parameter Description
ClassNotFoundException if none of the ClassLoaders is able to found the reuested class

Return

Class loaded class

Declaration

public static Class classForName(String className) throws ClassNotFoundException 

Method Source Code

//package com.java2s;
/**//from  w w  w.  ja  va 2  s.  c om
 * Licensed under the Artistic License; you may not use this file
 * except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://displaytag.sourceforge.net/license.html
 *
 * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

public class Main {
    /**
     * Tries to load a class with more classloaders. Can be useful in J2EE applications if jar is loaded from a
     * different classloader than user classes. If class is not found using the standard classloader, tries whit the
     * thread classloader.
     * @param className class name
     * @return Class loaded class
     * @throws ClassNotFoundException if none of the ClassLoaders is able to found the reuested class
     */
    public static Class classForName(String className) throws ClassNotFoundException {
        try {
            // trying with the default ClassLoader
            return Class.forName(className);
        } catch (ClassNotFoundException cnfe) {
            try {
                // trying with thread ClassLoader
                Thread thread = Thread.currentThread();
                ClassLoader threadClassLoader = thread.getContextClassLoader();
                return Class.forName(className, false, threadClassLoader);
            } catch (ClassNotFoundException cnfe2) {
                throw cnfe2;
            }
        }
    }
}

Related

  1. classForName(String className)
  2. classForName(String className)
  3. classForName(String className)
  4. classForName(String className)
  5. classForName(String className)
  6. classForName(String className)
  7. ClassForName(String className)
  8. classForName(String className, Class caller)
  9. classForName(String className, Class superClass)