Wanted to add jar to classpath without restarting REPL. Recalled java
reflection hack. Ported to Clojure.
user=> (import (org.apache.commons.cli Parser))
; fails with "#<CompilerException java.lang.ClassNotFoundException:
org.apache.commons.cli.Parser"
user=>
(import (
java.io File)
(
java.net URL URLClassLoader)
(java.lang.reflect Method))
(defn add-to-cp [#^String jarpath]
(let [#^URL url (.. (File. jarpath) toURI toURL)
url-ldr-cls (. (URLClassLoader. (into-array URL [])) getClass)
arr-cls (into-array Class [(. url getClass)])
arr-obj (into-array Object [url])
#^Method mthd (. url-ldr-cls getDeclaredMethod "addURL" arr-
cls)]
(doto mthd
(.setAccessible true)
(.invoke (ClassLoader/getSystemClassLoader) arr-obj))
(println (format "Added %s to classpath" jarpath))))
; any jar not on a classpath will do
(add-to-cp "c:/m2repo/commons-cli/commons-cli/1.0/commons-
cli-1.0.jar")
; import any class from loaded jar
(import (org.apache.commons.cli Parser))
Has anyone seen something similar? If no, do you think this could be
useful in clojure.contrib.repl-utils or else?