简体   繁体   English

Jar在类路径中

[英]Jar in the classpath

Is there a programmatically way to get the complete list of all jar in the classpath ? 是否有一种以编程方式获取类路径中所有jar的完整列表?

I need that because we have behavior differences between two platforms. 我需要这个,因为我们在两个平台之间存在行为差异。
One is managed by us, but the other is not and i need to know if there is or not the same jar. 一个由我们管理,但另一个不是,我需要知道是否有相同的罐子。

Depends on what do you exactly mean by classpath, there are in fact different kinds of classpaths : 取决于classpath的确切含义,实际上有不同类的类路径

  1. Boot Classpath 引导类路径

     System.getProperty("sun.boot.class.path") 
  2. Extension Classpath 扩展类路径

     System.getProperty("java.ext.dirs") 
  3. User defined Classpath 用户定义的Classpath

     System.getProperty("java.class.path") 

Which works for standard Java SE applications. 适用于标准Java SE应用程序。 For modular and Java SE it is more complicated. 对于模块化和Java SE,它更复杂。

Is there a programmatically way to get the complete list of all jar in the classpath ? 是否有一种以编程方式获取类路径中所有jar的完整列表?

This is one way to print out the current project classpath : 这是打印出当前项目类路径的一种方法:

ClassLoader cl = ClassLoader.getSystemClassLoader();
java.net.URL[] urls = ((java.net.URLClassLoader)cl).getURLs();
for (java.net.URL url: urls) {
    System.out.println(url.getFile());
}

If you need to determine which jar a class is loaded from : 如果您需要确定从哪个jar加载类

Class klass = ClassInTrouble.class;
CodeSource source = klass.getProtectionDomain().getCodeSource();
System.out.println(source == null ? klass : source.getLocation());

You can also get a list of all classes loaded in the JVM , if that's useful. 如果有用,您还可以获取JVM中加载的所有类的列表

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

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