Question

I've run into some problems following this question on SO: How do I programmatically compile and instantiate a Java class?

The following is my clojure translation:

(ns compile-and-load.core
  (:import [javax.tools JavaCompiler ToolProvider]
           [java.net URL URLClassLoader]))

(def src
  (str "package test;\n"
       "public class Test {\n"
       "  static { System.out.println(\"hello\");}\n"
       "  public Test() { System.out.println(\"world\");}}"))

(defn tmp-dir []
  (clojure.java.io/file (System/getProperty "java.io.tmpdir")))

(def tmp (tmp-dir))

(spit (str (.getAbsolutePath tmp) "/Test.java") src)


(.run (ToolProvider/getSystemJavaCompiler)
      nil nil nil
      (let [arr (make-array String 1)]
        (aset arr 0 (str (.getAbsolutePath tmp) "/Test.java"))
        arr))


(def cl (URLClassLoader.
         (let [arr (make-array URL 1)]
           (aset arr 0 (.toURL (.toURI tmp)))
           arr)))

(.loadClass cl "test.Test")

All is well up until the last line. There is a compiled Test.class and if I copy the file into the target/classes/test folder, I can load it. But with the last line, I get a ClassNotFoundException. What did I miss?

Était-ce utile?

La solution

I went around this problem with a dynamic loading library

Vinyasa

Here is a blog post about it: Dynamic reloading of java code in emacs/nrepl

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top