11

Is there a (compatible, if possible) way to determine the absolute path of a loaded Class?

Of course, this is not always possible (if you think of dynamically created classes), but if the loaded Class is inside a jar how to get the absolute path for this jar?

MRalwasser
  • 15,605
  • 15
  • 101
  • 147

2 Answers2

29
MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath()  

Fullcode:

    package org.life.java.so.questions;
   /**
     *
     * @author jigar
     */
    public class GetClassPath {
        public static void main(String[] args) {
            System.out.println(GetClassPath.class.getProtectionDomain().getCodeSource().getLocation().getPath());      
        }
    }

Output:

/C:/Documents%20and%20Settings/argus/My%20Documents/NetBeansProjects/temp/build/classes/

Or

ClassLoader loader = GetClassPath.class.getClassLoader();
System.out.println(loader.getResource("org/life/java/so/questions/GetClassPath.class"));
jmj
  • 237,923
  • 42
  • 401
  • 438
4

Try something like this:

SomeClass.class.getResource("/" + SomeClass.class.getName() + ".class").toString();

If the class is loaded from jar the result should be something like:

jar://myjar.jar!path/to/SomeClass.class
rodion
  • 14,729
  • 3
  • 53
  • 55
  • Class name must be transformed to a path by something like this: `SomeClass.class.getName().replace('.', '/')`.`com.stackoverflow.Test` -> `com/stackoverflow/Test` – mmdemirbas Jun 27 '19 at 10:21