Find where java class is loaded from

2018-12-31 10:07发布

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 very long and manual searching is not really an option. I recently had a problem where the classloader was loading an incorrect version of a class because it was on the classpath in two different places.

So how can I get the classloader to tell me where on disk the actual class file is coming from?

Edit: What about if the classloader actually fails to load the class due to a version mismatch (or something else), is there anyway we could find out what file its trying to read before it reads it?

10条回答
君临天下
2楼-- · 2018-12-31 10:24
getClass().getProtectionDomain().getCodeSource().getLocation();
查看更多
低头抚发
3楼-- · 2018-12-31 10:24

Edit just 1st line: Main.class

Class<?> c = Main.class;
String path = c.getResource(c.getSimpleName() + ".class").getPath().replace(c.getSimpleName() + ".class", "");

System.out.println(path);

Output:

/C:/Users/Test/bin/

Maybe bad style but works fine!

查看更多
荒废的爱情
4楼-- · 2018-12-31 10:25

Take a look at this similar question. Tool to discover same class..

I think the most relevant obstacle is if you have a custom classloader ( loading from a db or ldap )

查看更多
呛了眼睛熬了心
5楼-- · 2018-12-31 10:25

Typically, we don't what to use hardcoding. We can get className first, and then use ClassLoader to get the class URL.

        String className = MyClass.class.getName().replace(".", "/")+".class";
        URL classUrl  = MyClass.class.getClassLoader().getResource(className);
        String fullPath = classUrl==null ? null : classUrl.getPath();
查看更多
怪性笑人.
6楼-- · 2018-12-31 10:30

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

查看更多
姐姐魅力值爆表
7楼-- · 2018-12-31 10:33

This is what we use:

public static String getClassResource(Class<?> klass) {
  return klass.getClassLoader().getResource(
     klass.getName().replace('.', '/') + ".class").toString();
}

This will work depending on the ClassLoader implementation: getClass().getProtectionDomain().getCodeSource().getLocation()

查看更多
登录 后发表回答