Reputation: 1061
Is there a programmatically way to get the complete list of all jar in the classpath ?
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.
Upvotes: 3
Views: 317
Reputation: 5568
Is there a programmatically way to get the complete list of all jar in the classpath ?
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:
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.
Upvotes: 3
Reputation: 9707
Depends on what do you exactly mean by classpath, there are in fact different kinds of classpaths:
Boot Classpath
System.getProperty("sun.boot.class.path")
Extension Classpath
System.getProperty("java.ext.dirs")
User defined Classpath
System.getProperty("java.class.path")
Which works for standard Java SE applications. For modular and Java SE it is more complicated.
Upvotes: 4