Pablo's blog

A bit of this, a bit of that and a lot about computers

Printing the class-path in Clojure

Let’s compare how we print the class-path in Clojure and how we do it on Java.

In Clojure:

(println (seq (.getURLs (java.lang.ClassLoader/getSystemClassLoader))))

In Java:

import java.net.URL;
import java.net.URLClassLoader;

public class PrintClasspath {
    public static void main(String[] args) {
        //Get the System Classloader
        ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader();

        //Get the URLs
        URL[] urls = ((URLClassLoader)sysClassLoader).getURLs();

        for(int i=0; i< urls.length; i++)
        {
            System.out.println(urls[i].getFile());
        }
    }
}

To be fair, the output is not the same, but the effect is.

Advertisement

Single Post Navigation

8 thoughts on “Printing the class-path in Clojure

  1. Cool one liner. I’m just starting in on Clojure and played around until I could get the Clojure version to print in the same format as your Java version:

    (doseq [url (seq (.getURLs (java.lang.ClassLoader/getSystemClassLoader)))]
      (println (.getFile url)))
    

    Love it!
    .-= Matt“s last blog: The super easy way to use Emacs and Slime with Clojure =-.

  2. Martin on said:

    This might not work in all cases.
    You could also want:

    (import 'clojure.pprint)
    (pprint (seq (.getURLs (->  (Thread.currentThread)  (.getContextClassLoader)))))
    
    • Martin on said:

      Sorry:

      (use 'clojure.pprint)
      (import 'java.lang.Thread)
      (pprint (seq (.getURLs (-> (Thread/currentThread) (.getContextClassLoader)))))
      
      • Martin: syntactic variant on your example:

        (use 'clojure.pprint)
        (import 'java.lang.Thread)
        (-> (Thread/currentThread) (.getContextClassLoader) (.getURLs) (seq) (pprint))
        
      • My code got messed with by WordPress and got quotes changed to backticks :( Don’t know how to format code in my comment, sorry.

      • I fixed it, thanks for the code.

  3. this code worked fine with the older version of clojure. I tried it with the newer one but unfortunately, it didn’t work out. What could be the issue??

    • It works for me in Clojure 1.2.1, what error are you getting?

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

Please log in to WordPress.com to post a comment to your blog.

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 329 other followers