Nelz's Blog

Mah blogginess

Which Filesystem JAR Is a Class From?

In my environment, a test was blowing up. In my coworkers, it was working fine. On inspection, it seems my environment was expecting a different version of a class. How do I figure out what JAR the new/incorrect requirements are coming from?

I found this blog post, and it helped me greatly: From which Jar a Class was loaded?

I used this info to write the following utility:

package net.nelz.utils;

import javax.activation.*;
import java.security.*;
import java.net.*;

public class ClassFinder {
    public static String findClassOnFilesystem(final String className) {

        try {
            final Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className);

            return ClassFinder.findClassOnFilesystem(clazz);
        } catch (ClassNotFoundException ex) {

            return "Class:" + className + " - CLASS NOT FOUND!";
        }

    }

    public static String findClassOnFilesystem(final Class clazz) {

        final ProtectionDomain pDomain = clazz.getProtectionDomain();
        final CodeSource cSource = pDomain.getCodeSource();

        final URL loc = cSource.getLocation();
        final String result = clazz.toString() + " - " + loc;

        System.out.println(result);
        return result;

    }
}

Additionally, after finding this solution, a coworker pointed me to the Dependency Finder as another tool that can help diagnose classpath issues.