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

In Clojure:

[sourcecode lang=”clojure”]
(println (seq (.getURLs (java.lang.ClassLoader/getSystemClassLoader))))
[/sourcecode]

In Java:

[sourcecode lang=”clojure”]
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());
}
}
}
[/sourcecode]

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


Share:


Comments

9 responses to “Printing the class-path in Clojure”

  1. Matt Avatar

    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:

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

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

  2. Martin Avatar
    Martin

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

    [sourcecode lang=”clojure”]
    (import ‘clojure.pprint)
    (pprint (seq (.getURLs (-> (Thread.currentThread) (.getContextClassLoader)))))
    [/sourcecode]

    1. Martin Avatar
      Martin

      Sorry:
      [sourcecode lang=”clojure”]
      (use ‘clojure.pprint)
      (import ‘java.lang.Thread)
      (pprint (seq (.getURLs (-> (Thread/currentThread) (.getContextClassLoader)))))
      [/sourcecode]

      1. Eugene Koontz (@hadooplearnings) Avatar

        Martin: syntactic variant on your example:

        [sourcecode lang=”clojure”]
        (use ‘clojure.pprint)
        (import ‘java.lang.Thread)
        (-> (Thread/currentThread) (.getContextClassLoader) (.getURLs) (seq) (pprint))
        [/sourcecode]

      2. Eugene Koontz (@hadooplearnings) Avatar

        My code got messed with by WordPress and got quotes changed to backticks :( Don’t know how to format code in my comment, sorry.

      3. Pablo Avatar

        I fixed it, thanks for the code.

  3. sticker printing Avatar

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

    1. Pablo Avatar

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

  4. […] You can also verify the jfxrt.jar file has been included in the classpath with this line I got from here. […]

Leave a Reply to Martin Cancel reply

Your email address will not be published. Required fields are marked *