Wednesday, October 04, 2017

Dump Java class loaders including JAR physical paths

private static Iterator list(ClassLoader CL)
        throws NoSuchFieldException, SecurityException,
        IllegalArgumentException, IllegalAccessException {
    Class CL_class = CL.getClass();
    while (CL_class != java.lang.ClassLoader.class) {
        CL_class = CL_class.getSuperclass();
    }
    java.lang.reflect.Field ClassLoader_classes_field = CL_class
            .getDeclaredField("classes");
    ClassLoader_classes_field.setAccessible(true);
    Vector classes = (Vector) ClassLoader_classes_field.get(CL);
    return classes.iterator();
}
 
private void dumpClasses() {
    ClassLoader myCL = Thread.currentThread().getContextClassLoader();
    while (myCL != null) {
        log.warn("===> ClassLoader: " + myCL);
        try {
            for (Iterator iter = list(myCL); iter.hasNext();) {
                Class clazz = (Class) iter.next();
                log.warn("======> " + clazz.getName() + " @ "
                         + clazz.getProtectionDomain().getCodeSource().getLocation());
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        myCL = myCL.getParent();
    }
}