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?

1

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Actually, any JVM, since -verbose is a required flag, is it not. It's the -X flags that are vendor dependent.
17

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 :) )

1 Comment

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? :)
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

Comments

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.

2 Comments

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.
How would one go about printing the class path? The link you provide is broken.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.