Where on the file system was my Java class loaded from?

瘦欲@ 提交于 2019-11-27 19:05:44

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 :) )

public static URL getClassURL(Class klass) {
    String name = klass.getName();
    name = "/" + convertClassToPath(name);
    URL url = klass.getResource(name);
    return url;
}

public static String convertClassToPath(String className) {
    String path = className.replaceAll("\\.", "/") + ".class";
    return path;
}

Just stick this somewhere, and pass it the Class object for the class you want to find the definition of. It should work regardless of where it called from, since it calls getResource() on the class being searched for.

public static void main(String[] args) {
    System.out.println(getClassURL(String.class));       
}

Sample output: jar:file:/System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Classes/classes.jar!/java/lang/String.class

As the class needs to come from somewhere in the class path, I would recommend to simply print the class path and check if there's an older version of you class somewhere.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!