gpt4 book ai didi

java - 获取有效的类路径

转载 作者:行者123 更新时间:2023-11-30 03:34:59 25 4
gpt4 key购买 nike

如何从 Java 应用程序内部打印“有效”类路径?

这段代码:

public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);

ClassLoader x = ClassLoader.getSystemClassLoader();
URL[] urls = ((URLClassLoader)x).getURLs();
for (URL y : urls)
System.out.println(y);
}

输出:

file:/usr/share/java/plexus-classworlds2-2.5.1.jar

我希望在类路径中看到更多项目,包括 META-INF 和 WEB-INF 文件夹。

如何打印“有效”类路径?

-----编辑

我使用的解决方案(基于答案):

public static void main(String[] args) {
ClassLoader x = Thread.currentThread().getContextClassLoader();
URL[] urls = ((URLClassLoader)x).getURLs();
for (URL y : urls)
System.out.println(y);
}

最佳答案

因此,您本质上是希望进行应用程序资源查找/搜索。

Servlet 有方法获取 Servlet 容器内的资源。您可以使用ServletContext获取资源。

例如

ServletContext context = getServletConfig().getServletContext(); //ONLY if you're inside a Servlet.
String[] paths = context.getResourcePaths();
if (paths != null) {
for (String path : paths) {
URL resource = context.getResource(path);

//BLAH BLAH BLAH here
}
}

这将允许您访问 Web 应用程序资源,包括 META-INFWEB-INF 文件夹内的资源。

对于系统资源和Classpath资源,您需要使用ClassLoader;

ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
ClassLoader applicationClassLoader = Thread.currentThread().getContextClassLoader();
//Follow the examples you've used above.

对于 JARS 内的资源,您需要使用 URLClassLoader 并打开其连接并获取 JarFile 并迭代其所有条目,如下所示:

JarURLConnection connection = (JarURLConnection) url.openConnection();
JarFile file = connection.getJarFile();
Enumeration<JarEntry> entries = file.entries();
while (entries.hasMoreElements()) {
JarEntry e = entries.nextElement();
if (e.getName().startsWith("com")) {
// ...
}
}

我希望这会有所帮助。

关于java - 获取有效的类路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28212647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com