简体   繁体   English

如何在仅给出jar文件名的类路径中获取jar文件的绝对路径?

[英]How to get the absolute path of a jar file in classpath given ONLY the jar file name?

I am aware of getting the path of the jar that contains a specific class 我知道要获取包含特定类的jar的路径

<ClassName>.class.getProtectionDomain().getCodeSource().getLocation()

This is well explored in other SO questions. 在其他SO问题中对此进行了很好的探讨。


My question is : 我的问题是:

"How to get the path of the JAR file in the classpath given ONLY the JAR FILE NAME . “如何获得给定的只有 JAR文件名 的类路径的JAR文件的路径。

If you are looking to find the path to the currently running jar, try this 如果您要查找当前正在运行的jar的路径,请尝试以下操作

new File("", jarName);

If you are looking for something else in the classpath, you could use the same strategy, assuming that they are in the same directory as the jar. 如果要在类路径中查找其他内容,则可以使用相同的策略,假设它们与jar处于同一目录中。

However, if you have set the classpath, either by command line or in the manifest, it might be a little bit more complicated. 但是,如果通过命令行或清单设置类路径,则可能会有些复杂。

This is an example that I found on some website: 这是我在某些网站上找到的示例:

ClassLoader cl = ClassLoader.getSystemClassLoader();

URL[] urls = ((URLClassLoader)cl).getURLs();

This will get a list of absolute URLs that point to everything that has been loaded. 这将获得一个指向所有已加载内容的绝对URL列表。 All that you have to do is do url.getFile() 您要做的就是做url.getFile()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM