使用線程上下文類加載器加載class

 範例: 

public class RequestUtils {

  /**
     * <p>Return the <code>Class</code> object for the specified fully
     * qualified class name, from this web application's class loader.</p>
     *
     * @param className Fully qualified class name to be loaded
     * @return Class object
     * @throws ClassNotFoundException if the class cannot be found
     */
    public static Class applicationClass(String className)
        throws ClassNotFoundException {
        return applicationClass(className, null);
    }

    /**
     * <p>Return the <code>Class</code> object for the specified fully
     * qualified class name, from this web application's class loader.</p>
     *
     * @param className   Fully qualified class name to be loaded
     * @param classLoader The desired classloader to use
     * @return Class object
     * @throws ClassNotFoundException if the class cannot be found
     */
    public static Class applicationClass(String className,
        ClassLoader classLoader)
        throws ClassNotFoundException {
        if (classLoader == null) {
            // Look up the class loader to be used
            classLoader = Thread.currentThread().getContextClassLoader();

            if (classLoader == null) {
                classLoader = RequestUtils.class.getClassLoader();
            }
        }

        System.out.println(classLoader.loadClass(className).getName());

        // Attempt to load the specified class
        return (classLoader.loadClass(className));
    }
   
    public static void main(String[] args) {
     
     try {
   RequestUtils.applicationClass("cn.ehome.blog.util.PropertyMessageResources");
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }
    }
}

輸出結果:

cn.ehome.blog.util.PropertyMessageResources

 

發佈了6 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章