I have a javaagent jar that I put on the bootclasspath using
Boot-Class-Path: myagent.jar
inside the MANIFEST.MF file.
I need to find out the directory on the filesystem in which the jar is located.
However the method described for this here doesnt seem to work for me:
new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
In this case the ProtectionDomain.getCodeSource() returns null. I guess this is happening because the jar has been put on the boot classpath. Because of this I also cannot do MyClass.getClassLoader() to get the resource location.
I am using Java 6.
Can anyone tell how to get the location of the jar?
You can use the System class loader to find classes on the boot class path. For example, this
Will print out something like,
To find the location of
MyClass.classon disk, doUpdate 2020-06-29 by kriegaex: Rather than writing a new answer to this old question, I want to enhance or update this very good answer, also taking account paths with spaces and Java 9+ modules.
Here is a method returning the class file path as a
Fileinstance. If a class file is part of a JAR or Java runtime module (URL starts with protocoljrt:), it just returns the paths to the JAR or to the JMOD file, which is something you might not want, but it is just a showcase you can edit to your heart’s content. Of course this is still hacky, e.g. not considering classes loaded from a web URL instead of from file, but you get the idea.When I call this from one of my IntelliJ IDEA projects with JDK 14 installed under a path containing spaces and deliberately adding a JAR also containing a path with spaces for testing, this code…
… yields this console output: