liveBook · Manning

Gen-class

As explained in Clojure: The Essential Reference

gen-class is a Clojure facility that generates a named Java class from Clojure declarations and implementations.

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

How Clojure: The Essential Reference covers it

How deep it goes
Explains delegated implementations, generation options, AOT compilation, and REPL limitations, but not the full option set.
Examples
Demonstrates book.GenClass, :main true, -main, compile, Java invocation, and generated files under *compile-path*.
What it assumes
Assumes familiarity with Clojure namespaces and functions, while demonstrating compilation and Java-facing class generation.
What you can do after
Build it from scratch by declaring gen-class, defining namespace functions, compiling the namespace, and invoking the resulting Java class.
How it connects
Connects generated Java classes with gen-interface, compile, namespaces, inheritance, interfaces, and AOT compilation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.