asicfr
asicfr

Reputation: 1061

Jar in the classpath

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

Answers (2)

gknicker
gknicker

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

Crazyjavahacking
Crazyjavahacking

Reputation: 9707

Depends on what do you exactly mean by classpath, there are in fact different kinds of classpaths:

  1. Boot Classpath

    System.getProperty("sun.boot.class.path")
    
  2. Extension Classpath

    System.getProperty("java.ext.dirs")
    
  3. 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

Related Questions