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?
The class files actually reside as jar files inside the Java distribution being used. Most files are in rt. jar (runtime).
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.
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.
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.
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.
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 :) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With