Axiom255
Axiom255

Reputation: 1397

Get effective classpath

How can the "effective" classpath be printed from inside of a Java application?

This code:

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);
}

Outputs:

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

I would expect to see more items in the classpath, including the META-INF and WEB-INF folders.

How can the "effective" classpath be printed?

----- Edit

The solution I used (based on the answer):

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

Upvotes: 1

Views: 499

Answers (1)

Buhake Sindi
Buhake Sindi

Reputation: 89189

So, you're essentially looking to do an application resource lookup/search.

Servlets has ways to obtain resources within a Servlet Container. You can get resources by using ServletContext.

E.g.

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
    }
}

This will allow you to access your web application resources, including those inside your META-INF and WEB-INF folders.

For System resource and Classpath resource, you will need to use ClassLoader;

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

For resources inside JARS, you will need to use a URLClassLoader and open it's connection and get the JarFile and iterate through all its entries, like so:

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")) {
        // ...
    }
}

I hope this helps.

Upvotes: 2

Related Questions