Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where on the file system was my Java class loaded from?

Tags:

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?

like image 213
shsteimer Avatar asked Apr 22 '09 23:04

shsteimer


People also ask

Where are the class files stored in Java?

The class files actually reside as jar files inside the Java distribution being used. Most files are in rt. jar (runtime).

Which jar is my class loaded from?

The, the idea is to use find on the root of your classpath to locate all jars, then runs findclass.sh on all found jars to look for a match. It doesn't handle multi-directories, but if you carefully choose the root you can get it to work.

Where are classes loaded by JVM?

The most straightforward approach for listing all classes loaded would be to log that in a console output or file. [Opened /Library/Java/JavaVirtualMachines/jdk1. 8.0_241. jdk/Contents/Home/jre/lib/rt.

How do you find the path of a class?

We can use the getClass() method of Object class in Java that returns the currently running class, which further can be used with the getPath() method to get the path of the current working directory.


2 Answers

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.

like image 126
Joachim Sauer Avatar answered Nov 07 '22 13:11

Joachim Sauer


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

like image 24
Chris Thornhill Avatar answered Nov 07 '22 13:11

Chris Thornhill