其一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);
}