ClassLoader获取的两种方式

来源:互联网 发布:ubuntu 启动 黑屏 u盘 编辑:程序博客网 时间:2024/06/16 03:48

其一java 1.2以及之后:

Method method = Thread.class.getMethod("getContextClassLoader", null);

ClassLoader cl = (ClassLoader) method.invoke(Thread.currentThread(), null);

通用:ClassLoader cl = className.class.getClassLoader();

 

 

log4j中的loader#getTCL源码实例:

    /**
     * Get the Thread Context Loader which is a JDK 1.2 feature. If we are
     * running under JDK 1.1 or anything else goes wrong the method returns
     * <code>null<code>.
     *
     * */
    private static ClassLoader getTCL()
        throws IllegalAccessException, InvocationTargetException
    {

        // Are we running on a JDK 1.2 or later system?
        Method method = null;
        try
        {
            method = Thread.class.getMethod("getContextClassLoader", null);
        }
        catch (NoSuchMethodException e)
        {
            // We are running on JDK 1.1
            return null;
        }

        return (ClassLoader)method.invoke(Thread.currentThread(), null);
    }

 

原创粉丝点击