从类中获取完整的类路径
我正在寻找一种实用方法,以便给定的类将返回外部运行该类所需的完整类路径。这意味着类所在的 jar 以及它使用的类的所有 jar(或文件夹)。
更新:有一些工具可以分析 .class 文件以查找依赖项。这不是我要找的。我正在寻找在已加载的类上使用 Java 反射 API 的东西。我会选择分析字节码的东西,如果它递归地进入通过类加载器找到的类
I'm looking a utility method so that given a class will return the full classpath required to run this class externally. This means the jar the class is in as well as all jars (or folders) of classes that it uses.
UPDATE: there are tools that analyze .class files to find dependencies. This is not what I'm looking for. I'm looking for something that uses Java's reflection API on an already loaded class. I'll settle for something that analyzes byte code, if it goes recursively into classes it finds through the class loader
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对于这一点,反思不会对你有太大帮助。您将需要分析字节码以查找依赖项。
更新:
那么好吧。我正在使用几年前制作的一个库,您可以在此处下载。
以下代码:
将为您提供一个类的所有依赖项。当应用于 org.jedo.classfile.ClassFile 时,它会产生以下输出:
后面是很多系统类。您需要过滤掉系统类,并解析其他 url 以提取 .jar 文件(如果它是 jar: url)或目录(如果它是 file: url)。
Reflection will not help you a lot for this one. You will need to analyse the byte code to find dependencies.
UPDATE:
Alright then. I am using a library that I made years ago, that you can download here.
The following code:
Will give you all the dependencies of a class. When applied to org.jedo.classfile.ClassFile, it produces the following output:
Followed by a lot of system classes. You need to filter out system classes, and parse the other urls to extract either the .jar file if it is a jar: url, or the directory if it is a file: url.
我认为这是不可能的。当然,反射 API 不支持它。
你可以找到一个classes类加载器,但你无法找到:
实际上,这有点夸大了事情:
但这一切都非常复杂,我预计它在某些情况下是不可靠的。
I don't think this is possible. Certainly, the reflection APIs don't support it.
You can find out a classes classloader, but you cannot find out:
Class.forName()
.Actually, this overstates things somewhat:
But this is all extremely complicated, and I'd expect it to be unreliable under certain circumstances.
在某些情况下,您无法在使用课程之前确定这一点。
There are cases when you cannot determine this prior to using your class.
这并不总是可知的。例如,可以在运行时动态创建类,然后使用自定义
ClassLoader
加载。我不相信 Java 会存储这些信息。
This cannot always be known. For instance, a class can be dynamically created at run time and then loaded with a custom
ClassLoader
.I do not believe Java stores this information.