liveBook · Manning

Gen-interface

As explained in Clojure: The Essential Reference

gen-interface is a Clojure macro that generates a Java interface from a name, parent interfaces, and method signatures.

gen-interface is a Clojure macro for generating a Java interface. It separates interface declaration from concrete inheritance, supporting “a-la carte polymorphism”: a type can adopt the generated contract without inheriting an implementation. The macro accepts :name, :extends, and :methods options and returns the generated type. section 15.0 section 15.3

Use the key-value options to define the interface contract:

  • :name supplies the interface’s qualified name, such as "user.BookInterface". section 15.3
  • :extends lists parent interfaces, allowing the generated interface to inherit existing interface contracts. section 15.3
  • :methods specifies the method signatures exposed by the interface. section 15.3

Generate and implement a marker interface

(gen-interface :name "user.BookInterface" :extends [java.io.Serializable]) (ancestors user.BookInterface) ;; #{java.io.Serializable} (reify user.BookInterface Object (toString [_] "A marker interface for books.")) ;; #object[user$eval20 ... "A marker interface for books."] The example creates user.BookInterface, makes it extend java.io.Serializable, verifies that relationship with ancestors, and implements it with reify. gen-interface declares the contract; reify supplies an implementation for an object. section 15.0

How Clojure: The Essential Reference covers it

How deep it goes
Defines three options and demonstrates inheritance and implementation, but does not detail method-signature forms or compilation behavior.
Examples
Uses user.BookInterface, java.io.Serializable, ancestors, and reify to demonstrate generation, inheritance, inspection, and implementation.
What it assumes
Assumes familiarity with Clojure macros and Java interfaces while demonstrating inheritance inspection and interface implementation.
What you can do after
Build Java interfaces from names, parent interfaces, and method signatures, then implement them with interface-oriented Clojure constructs.
How it connects
Connects Java interfaces with gen-class, deftype, definterface, proxy, reify, defrecord, and protocols.

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.