26

I think this is a situation every Java programmer runs into if they do it long enough. You're doing some debugging and make a change to class. When you go to re-run the program, these changes don't seem to be picked up but rather the old class still seems to be running. You clean and rebuild everything, same issue. Sometimes, this can come down to a classpath issue, of the same class being on the classpath more than once, but there doesn't seem to be an easy way to figure out where the class being loaded is coming from...

Is there any way to find the file path for the class that was loaded? Preferable something that would work either if the class was loaded from a .class file or a .jar file. Any Ideas?

shsteimer
  • 28,436
  • 30
  • 79
  • 95
  • This is almost the same as the following question, which has slightly different answers: http://stackoverflow.com/questions/947182/how-to-explore-which-classes-are-loaded-from-which-jars – Urban Vagabond Aug 07 '12 at 05:42

4 Answers4

31

Simply run java using the standard command line switch"-verbose:class" (see the java documentation). This will print out each time a class is loaded and tell you where it's loaded from.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
15

If you wanted to do it programmatically from inside the application, try:

URL loc = MyClass.class.getProtectionDomain().getCodeSource().getLocation();

(Note, getCodeSource() may return null, so don't actually do this all in one line :) )

Chris Thornhill
  • 5,321
  • 1
  • 24
  • 21
6
public static URL getClassURL(Class klass) {
    String name = klass.getName();
    name = "/" + convertClassToPath(name);
    URL url = klass.getResource(name);
    return url;
}

public static String convertClassToPath(String className) {
    String path = className.replaceAll("\\.", "/") + ".class";
    return path;
}

Just stick this somewhere, and pass it the Class object for the class you want to find the definition of. It should work regardless of where it called from, since it calls getResource() on the class being searched for.

public static void main(String[] args) {
    System.out.println(getClassURL(String.class));       
}

Sample output: jar:file:/System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Classes/classes.jar!/java/lang/String.class

avalys
  • 3,662
  • 4
  • 25
  • 22
0

As the class needs to come from somewhere in the class path, I would recommend to simply print the class path and check if there's an older version of you class somewhere.

lothar
  • 19,853
  • 5
  • 45
  • 59
  • 3
    Actually, no longer true. There's the system classes, the extension directories (yes, plural), dynamically extensible class loaders (ala URLClassLoader). These days, where the class actually came from is possibly quite complicated. – Lawrence Dol Apr 23 '09 at 03:39
  • How would one go about printing the class path? The link you provide is broken. – Dezza Jul 10 '17 at 14:16