Cover by Brian Carper, Christophe Grand, Chas Emerick

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Defining Classes and Implementing Interfaces

Being able to call Java methods and instantiate classes is a good start, but you often need to define classes as well, implementing interfaces and sometimes extending an existing class. Clojure provides an array of class definition facilities, each of which offers a mix of different capabilities suited for different use cases.

Table 9-3. Comparison of key features of Clojure forms that define Java classes[293]

 proxygen-classreifydeftypedefrecord

Returns an instance of an anonymous class?

Defines a named class?

Can extend an existing base class?

Can define new fields?

Provides default implementations of Object.equals, Object.hashcode, and various Clojure interfaces?

[293] If you know you need to define a new type in Clojure, but you’re not sure which type-definition form to use, refer to the flowchart designed specifically for this purpose at Chapter 18.

All of these forms can be used to define classes and implement interfaces. Some of these forms—deftype, defrecord, and reify—also serve unique roles within Clojure that are unrelated to interoperability with Java classes and interfaces. Thus, we discuss them separately in Chapter 6.

On the other hand, the remaining two—proxy and gen-class—exist solely to support these usages in interop scenarios; we’ll cover them here.

Instances of Anonymous Classes: proxy

proxy produces an instance of an anonymous class that implements any number of Java interfaces and/or a single concrete ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required