确定一个类来自哪个 JAR 文件

编程入门 行业动态 更新时间:2024-10-09 16:29:02
本文介绍了确定一个类来自哪个 JAR 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I am not in front of an IDE right now, just looking at the API specs.

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

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

I want to determine which JAR file a class is from. Is this the way to do it?

推荐答案

是的.它适用于除引导类加载器加载的类之外的所有类.另一种确定方法是:

Yes. It works for all classes except classes loaded by bootstrap classloader. The other way to determine is:

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

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

As notnoop pointed out klass.getResource() method returns the location of the class file itself. For example:

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

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

The getProtectionDomain().getCodeSource().getLocation() method returns the location of the jar file or CLASSPATH

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

更多推荐

确定一个类来自哪个 JAR 文件

本文发布于:2023-07-04 09:23:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1022353.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   JAR

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!