gen-class generates a named Java class whose methods delegate to Clojure function implementations in a surrounding namespace. It supports options for extended classes, implemented interfaces, and other Java-facing behavior. section 15.0 section 15.3
Use gen-class to:
- Place a class on the filesystem so Java can load and use it. section 15.3
- Expose a class or interface for Java extension, or extend and access existing Java classes. section 15.3
- Provide a main method for launching a Clojure application through Java tooling. section 15.3
gen-class is a macro intended for compilation rather than ordinary direct invocation. Calling it in a REPL produces no useful output: the declaration is evaluated while the runtime is bootstrapping, and a REPL normally has *compile-files* set to false. Compile a file containing the declaration instead. section 15.3
Generate a Java-launchable class
(spit (str *compile-path* "/bookgenclass.clj") "(ns bookgenclass) (gen-class :name book.GenClass :main true) (defn -main [& args] (println \"Hello from Java!\"))") (compile 'bookgenclass) ;; bookgenclass (import 'book.GenClass) (GenClass/main (make-array String 0)) ;; Hello from Java! section 15.3
(spit (str *compile-path* "/bookgenclass.clj") ; #1
"(ns bookgenclass)
(gen-class :name book.GenClass
:main true)") ; #2
(compile 'bookgenclass) ; #3
;; bookgenclass
Inspect the compilation path after compiling a namespace containing gen-class to find the generated Java class files. section 15.3
