views:

498

answers:

4

I think this is a situation every java programmer runs into if they do it long enough. Your doing some debugging and make a changes 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?

+7  A: 

When you're using the Sun JVM, then 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
Actually, any JVM, since -verbose is a required flag, is it not. It's the -X flags that are vendor dependent.
Software Monkey
Thanks, I mentioned that.
Joachim Sauer
+1  A: 

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
getProtectionDomain may also return null (typically for boot classes). My question is, if the changes aren't showing up, how do you run this code? :)
Tom Hawtin - tackline
+1  A: 

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
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.
Software Monkey
+2  A: 
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