首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >确定类来自哪个JAR文件

确定类来自哪个JAR文件
EN

Stack Overflow用户
提问于 2009-12-31 11:45:57
回答 5查看 95K关注 0票数 169

我现在并没有站在IDE的前面,只是在看API规范。

代码语言:javascript
复制
CodeSource src = MyClass.class.getProtectionDomain().getCodeSource();
if (src != null) {
    URL jar = src.getLocation();
}

我想确定一个类来自哪个JAR文件。这是做这件事的方法吗?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2009-12-31 12:04:57

是。它适用于除bootstrap类加载器加载的类以外的所有类。另一种确定方法是:

代码语言:javascript
复制
Class klass = String.class;
URL location = klass.getResource('/' + klass.getName().replace('.', '/') + ".class");

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

代码语言:javascript
复制
jar:file:/jdk/jre/lib/rt.jar!/java/lang/String.class
file:/projects/classes/pkg/MyClass$1.class

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

代码语言:javascript
复制
file:/Users/home/java/libs/ejb3-persistence-1.0.2.GA.jar
file:/projects/classes
票数 210
EN

Stack Overflow用户

发布于 2009-12-31 12:07:46

Lombok Patcher LiveInjector.java中检出LiveInjector.findPathJar()。请注意,在特殊情况下,文件实际上不在jar中,您可能想要更改这种情况。

代码语言:javascript
复制
/**
 * 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.");
    }
}
票数 13
EN

Stack Overflow用户

发布于 2019-05-06 15:12:53

使用

代码语言:javascript
复制
String path = <Any of your class within the jar>.class.getProtectionDomain().getCodeSource().getLocation().getPath(); 

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1983839

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档