Find where java class is loaded from

前端 未结 11 1266
独厮守ぢ
独厮守ぢ 2020-11-22 06:22

Does anyone know how to programmaticly find out where the java classloader actually loads the class from?

I often work on large projects where the classpath gets v

相关标签:
11条回答
  • 2020-11-22 06:41

    This approach works for both files and jars:

    Class clazz = Class.forName(nameOfClassYouWant);
    
    URL resourceUrl = clazz.getResource("/" + clazz.getCanonicalName().replace(".", "/") + ".class");
    InputStream classStream = resourceUrl.openStream(); // load the bytecode, if you wish
    
    0 讨论(0)
  • 2020-11-22 06:49

    Assuming that you're working with a class named MyClass, the following should work:

    MyClass.class.getClassLoader();
    

    Whether or not you can get the on-disk location of the .class file is dependent on the classloader itself. For example, if you're using something like BCEL, a certain class may not even have an on-disk representation.

    0 讨论(0)
  • 2020-11-22 06:51
    getClass().getProtectionDomain().getCodeSource().getLocation();
    
    0 讨论(0)
  • 2020-11-22 06:54

    Here's an example:

    package foo;
    
    public class Test
    {
        public static void main(String[] args)
        {
            ClassLoader loader = Test.class.getClassLoader();
            System.out.println(loader.getResource("foo/Test.class"));
        }
    }
    

    This printed out:

    file:/C:/Users/Jon/Test/foo/Test.class
    
    0 讨论(0)
  • 2020-11-22 06:54

    Another way to find out where a class is loaded from (without manipulating the source) is to start the Java VM with the option: -verbose:class

    0 讨论(0)
提交回复
热议问题