如何找出类在运行时的起源?

时间:2014-08-09 08:28:38

标签: java maven classloader

我有这个奇怪的问题,其中来自某些传递依赖的类在运行时不断出现,从(正确的)第一级依赖项中影响该类的较新版本,即使我认为我确定了从我声明的所有其他依赖项中排除旧版本(这是在Maven / IntelliJ设置中)

更具体地说,在运行时,应用程序失败并显示NoClassDefFoundError,因为在类加载期间加载了拥有类的错误版本,其具有在较新版本的库中不存在的类型的字段该类定义于。举例说明:

// lib.jar:wrong-version
class Owner {
  private SomeType f;
}

// lib.jar:new-version
class Owner {
  private OtherType f;
}

在运行时,类加载器找到对符号Owner的引用,并尝试加载具有SomeType的版本,而该版本不再存在。即使我将wrong-version排除在哪里,我也可以发现它。

我还运行了mvn dependency:tree以查看旧版本是否仍在某个地方被提取,但事实并非如此!

为了进一步调试这个,我想知道是否有办法找出类加载器从哪个类读取特定类,即哪个文件?那可能吗?或者甚至更好,建立一个定义某个符号的起源列表,以防它被定义多次?

很抱歉,如果这很模糊,但问题相当模糊。

2 个答案:

答案 0 :(得分:1)

如果您知道班级的完全限定名称,例如somelib.Owner,您可以尝试在代码中调用以下内容:

public void foo() {
    URL url = somelib.Owner.class.getClassLoader().getResource("somelib/Owner.class");
    System.out.println(url);
}

答案 1 :(得分:1)

以下代码将搜索特定类的整个类路径。如果没有参数,它将转储它找到的每个类,然后你可以管道grep或重定向到一个文件。它看起来在罐子里......

用法:WhichClassWhichClass package.name(请注意没有.class

对缺乏评论表示道歉......

import java.io.File;
import java.io.IOException;

import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public final class WhichClass {

  private WhichClass() {
  }

  static Vector<String> scratchVector;

  public static void main(final String[] argv) {
    Vector v;

    if ((argv.length == 0) || "-all".equals(argv[0])) {
      v = findClass(null);
    } else {
      v = findClass(argv[0]);
    }

    for (int i = 0; i < v.size(); i++) {
      System.out.println(v.elementAt(i));
    }
  }

  static String className(final String classFile) {
    return classFile.replace('/', '.').substring(0, classFile.length() - ".class".length());
  }

  static Vector findClass(final String className) {
    if (className != null) {
      scratchVector = new Vector<String>(5);
    } else {
      scratchVector = new Vector<String>(5000);
    }

    findClassInPath(className, setupBootClassPath());
    findClassInPath(className, setupClassPath());

    return scratchVector;
  }

  static void findClassInPath(final String className, final StringTokenizer path) {
    while (path.hasMoreTokens()) {
      String pathElement = path.nextToken();

      File pathFile = new File(pathElement);

      if (pathFile.isDirectory()) {
        try {
          if (className != null) {
            String pathName = className.replace('.', System.getProperty("file.separator").charAt(0)) + ".class";

            findClassInPathElement(pathName, pathElement, pathFile);
          } else {
            findClassInPathElement(className, pathElement, pathFile);
          }
        } catch (IOException e) {
          e.printStackTrace();
        }
      } else if (pathFile.exists()) {
        try {
          if (className != null) {
            String pathName = className.replace('.', '/') + ".class";

            ZipFile  zipFile  = new ZipFile(pathFile);
            ZipEntry zipEntry = zipFile.getEntry(pathName);
            if (zipEntry != null) {
              scratchVector.addElement(pathFile + "(" + zipEntry + ")");
            }
          } else {
            ZipFile     zipFile = new ZipFile(pathFile);
            Enumeration entries = zipFile.entries();

            while (entries.hasMoreElements()) {
              String entry = entries.nextElement().toString();

              if (entry.endsWith(".class")) {
                String name = className(entry);

                scratchVector.addElement(pathFile + "(" + entry + ")");
              }
            }
          }
        } catch (IOException e) {
          System.err.println(e + " while working on " + pathFile);
        }
      }
    }
  }

  static void findClassInPathElement(final String pathName, final String pathElement, final File pathFile)
    throws IOException {
    String[] list = pathFile.list();

    for (int i = 0; i < list.length; i++) {
      File file = new File(pathFile, list[i]);

      if (file.isDirectory()) {
        findClassInPathElement(pathName, pathElement, file);
      } else if (file.exists() && (file.length() != 0) && list[i].endsWith(".class")) {
        String classFile = file.toString().substring(pathElement.length() + 1);

        String name = className(classFile);

        if (pathName != null) {
          if (classFile.equals(pathName)) {
            scratchVector.addElement(file.toString());
          }
        } else {
          scratchVector.addElement(file.toString());
        }
      }
    }
  }

  static StringTokenizer setupBootClassPath() {
    String classPath = System.getProperty("sun.boot.class.path");
    String separator = System.getProperty("path.separator");

    return new StringTokenizer(classPath, separator);
  }

  static StringTokenizer setupClassPath() {
    String classPath = System.getProperty("java.class.path");
    String separator = System.getProperty("path.separator");

    return new StringTokenizer(classPath, separator);
  }
}