我在SO上遇到这个问题时遇到了一些问题:How do I programmatically compile and instantiate a Java class?
以下是我的clojure翻译:
(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")
一直到最后一行都很好。有一个已编译的Test.class,如果我将文件复制到target / classes / test文件夹,我可以加载它。但是在最后一行,我得到了ClassNotFoundException
。我错过了什么?