【问题标题】:Determine which JAR file a class is from确定类来自哪个 JAR 文件
【发布时间】:2010-12-31 07:53:07
【问题描述】:

我现在不在 IDE 面前,只是查看 API 规范。

CodeSource src = MyClass.class.getProtectionDomain().getCodeSource();
if (src != null) {
    URL jar = src.getLocation();
}

我想确定一个类来自哪个 JAR 文件。是这样的吗?

【问题讨论】:

  • 有没有办法从控制台做到这一点?类似java -findjar -cp /some/path/with/libs/*.jar my.java.Class -> my.jar
  • @kub1x 请参阅my answer,了解从 (Linux) 控制台执行此操作的方法。我也在准备一个基于 javassist 的“findjar”等价物......

标签: java jar class classloader


【解决方案1】:

是的。它适用于除引导类加载器加载的类之外的所有类。另一种判断方法是:

Class klass = String.class;
URL location = klass.getResource('/' + klass.getName().replace('.', '/') + ".class");

正如notnoop 指出的klass.getResource() 方法返回类文件本身的位置。例如:

jar:file:/jdk/jre/lib/rt.jar!/java/lang/String.class
file:/projects/classes/pkg/MyClass$1.class

getProtectionDomain().getCodeSource().getLocation()方法返回jar文件或CLASSPATH的位置

file:/Users/home/java/libs/ejb3-persistence-1.0.2.GA.jar
file:/projects/classes

【讨论】:

  • 这使得假设邻接从类名到类文件的映射。它是否适用于匿名类?嵌套类?
  • 这指向类的 url 而不是 jar 本身。需要解析url才能找到jar文件。
  • @notnoop。我已经澄清了答案。
  • 感谢您的回答,它启发了我回答this question
  • 在上一个示例中,您将哪个参数传递给klass.getResource()
【解决方案2】:

Lombok Patcher LiveInjector.java 签出LiveInjector.findPathJar()。请注意,文件实际上并不存在于 jar 中的特殊情况,您可能需要更改它。

/**
 * If the provided class has been loaded from a jar file that is on the local file system, will find the absolute path to that jar file.
 * 
 * @param context The jar file that contained the class file that represents this class will be found. Specify {@code null} to let {@code LiveInjector}
 *                find its own jar.
 * @throws IllegalStateException If the specified class was loaded from a directory or in some other way (such as via HTTP, from a database, or some
 *                               other custom classloading device).
 */
public static String findPathJar(Class<?> context) throws IllegalStateException {
    if (context == null) context = LiveInjector.class;
    String rawName = context.getName();
    String classFileName;
    /* rawName is something like package.name.ContainingClass$ClassName. We need to turn this into ContainingClass$ClassName.class. */ {
        int idx = rawName.lastIndexOf('.');
        classFileName = (idx == -1 ? rawName : rawName.substring(idx+1)) + ".class";
    }

    String uri = context.getResource(classFileName).toString();
    if (uri.startsWith("file:")) throw new IllegalStateException("This class has been loaded from a directory and not from a jar file.");
    if (!uri.startsWith("jar:file:")) {
        int idx = uri.indexOf(':');
        String protocol = idx == -1 ? "(unknown)" : uri.substring(0, idx);
        throw new IllegalStateException("This class has been loaded remotely via the " + protocol +
                " protocol. Only loading from a jar on the local file system is supported.");
    }

    int idx = uri.indexOf('!');
    //As far as I know, the if statement below can't ever trigger, so it's more of a sanity check thing.
    if (idx == -1) throw new IllegalStateException("You appear to have loaded this class from a local jar file, but I can't make sense of the URL!");

    try {
        String fileName = URLDecoder.decode(uri.substring("jar:file:".length(), idx), Charset.defaultCharset().name());
        return new File(fileName).getAbsolutePath();
    } catch (UnsupportedEncodingException e) {
        throw new InternalError("default charset doesn't exist. Your VM is borked.");
    }
}

【讨论】:

  • 这似乎过于复杂,很难得到一些非常简单的东西。我只是坐下来尝试了我之前发现的东西,它似乎有效。只是想要一些验证。
  • 好吧。您的代码不处理引导类路径中的文件,并且 Chandra 的解决方案将 url 返回到文件而不是 jar 文件,因此您需要解析路径以找到 jar 文件。
【解决方案3】:
private String resourceLookup(String lookupResourceName) {



    try {

        if (lookupResourceName == null || lookupResourceName.length()==0) {
            return "";
        }
        // "/java/lang/String.class"

        // Check if entered data was in java class name format
        if (lookupResourceName.indexOf("/")==-1) {
            lookupResourceName = lookupResourceName.replaceAll("[.]", "/");
            lookupResourceName =  "/" + lookupResourceName + ".class";
        }

        URL url = this.getClass().getResource(lookupResourceName);
        if (url == null) {
            return("Unable to locate resource "+ lookupResourceName);

        }

        String resourceUrl = url.toExternalForm();

        Pattern pattern =
            Pattern.compile("(zip:|jar:file:/)(.*)!/(.*)", Pattern.CASE_INSENSITIVE);

        String jarFilename = null;
        String resourceFilename = null;
        Matcher m = pattern.matcher(resourceUrl);
        if (m.find()) {
            jarFilename = m.group(2);
            resourceFilename = m.group(3);
        } else {
            return "Unable to parse URL: "+ resourceUrl;

        }

        if (!jarFilename.startsWith("C:") ){
          jarFilename = "/"+jarFilename;  // make absolute path on Linux
        }

        File file = new File(jarFilename);
        Long jarSize=null;
        Date jarDate=null;
        Long resourceSize=null;
        Date resourceDate=null;
        if (file.exists() && file.isFile()) {

            jarSize = file.length();
            jarDate = new Date(file.lastModified());

            try {
                JarFile jarFile = new JarFile(file, false);
                ZipEntry entry = jarFile.getEntry(resourceFilename);
                resourceSize = entry.getSize();
                resourceDate = new Date(entry.getTime());
            } catch (Throwable e) {
                return ("Unable to open JAR" + jarFilename + "   "+resourceUrl +"\n"+e.getMessage());

            }

           return "\nresource: "+resourceFilename+"\njar: "+jarFilename + "  \nJarSize: " +jarSize+"  \nJarDate: " +jarDate.toString()+"  \nresourceSize: " +resourceSize+"  \nresourceDate: " +resourceDate.toString()+"\n";


        } else {
            return("Unable to load jar:" + jarFilename+ "  \nUrl: " +resourceUrl);

        }
    } catch (Exception e){
        return e.getMessage();
    }


}

【讨论】:

  • 上面的代码会找到路径上的任何资源。如果在 Jar 中会找到 jar,则打印 jar 的大小和日期以及 jar 中资源的大小和日期
【解决方案4】:

使用

String path = <Any of your class within the jar>.class.getProtectionDomain().getCodeSource().getLocation().getPath(); 

如果这包含多个条目,则执行一些子字符串操作。

【讨论】:

    【解决方案5】:

    对于 Linux,我正在使用一个小脚本来帮助我找到可以在 find -exec 中使用的类所在的 jar:

    findclass.sh:

    unzip -l "$1" 2>/dev/null | grep $2 >/dev/null 2>&1 && echo "$1"
    

    基本上,由于 jar 是 zip,unzip -l 将打印类资源列表,因此您必须将 . 转换为 /。你可以在脚本中用tr进行替换,但调用脚本时自己做也不会太麻烦。

    这个想法是在类路径的根目录上使用 find 来定位所有 jar,然后在所有找到的 jar 上运行 findclass.sh 以查找匹配项。

    它不处理多目录,但如果你仔细选择根目录,你可以让它工作。

    现在,找到哪个 jar 包含类 org.apache.commons.lang3.RandomUtils 以便您取消项目 (...):

    $ find ~/.m2/repository/ -type f -name '*.jar' -exec findclass.sh {} org/apache/commons/lang3/RandomUtils \;
    
    .m2/repository/org/apache/commons/commons-lang3/3.7/commons-lang3-3.7.jar
    .m2/repository/org/apache/commons/commons-lang3/3.6/commons-lang3-3.6.jar
    .m2/repository/org/apache/commons/commons-lang3/3.6/commons-lang3-3.6-sources.jar
    $
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-21
      • 2011-04-06
      • 2013-01-03
      • 1970-01-01
      • 2016-08-04
      相关资源
      最近更新 更多