Java 获取有效的类路径
如何从Java应用程序内部打印“有效”类路径 此代码:Java 获取有效的类路径,java,Java,如何从Java应用程序内部打印“有效”类路径 此代码: public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); ClassLoader x = ClassLoader.getSystemClassLoader(); URL[] urls = ((URLClassLoader)x).getURLs(); for
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文件夹
如何打印“有效”类路径
-----编辑
我使用的解决方案(基于答案):
因此,您实际上希望执行应用程序资源查找/搜索 Servlet有多种方法可以在Servlet容器中获取资源。您可以使用
ServletContext
获取资源
例如
这将允许您访问web应用程序资源,包括META-INF
和web-INF
文件夹中的资源
对于系统资源和类路径资源,您将需要使用ClassLoader
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
ClassLoader applicationClassLoader = Thread.currentThread().getContextClassLoader();
//Follow the examples you've used above.
对于JAR中的资源,您需要使用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")) {
// ...
}
}
JarURLConnection连接=(JarURLConnection)url.openConnection();
JarFile file=connection.getJarFile();
枚举条目=file.entries();
while(entries.hasMoreElements()){
JarEntry e=entries.nextElement();
if(例如getName().startsWith(“com”)){
// ...
}
}
我希望这会有所帮助。除了接受答案,如果你也对它进行投票,那就很酷了。答案是有效的,因为
getContextClassLoader()
将返回一个属于你容器范围的ClassLoader
,它在ServletContext
内部使用,因此我称它为applicationClassLoader
。
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
ClassLoader applicationClassLoader = Thread.currentThread().getContextClassLoader();
//Follow the examples you've used above.
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")) {
// ...
}
}