Cover by Brian Carper, Christophe Grand, Chas Emerick

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

Using Java Classes, Methods, and Fields

Clojure provides some simple forms for interoperating with its host’s classes, methods, and fields; this makes working with Java libraries within Clojure very natural, and certainly more concise than the equivalent Java code.

Table 9-1. Clojure interop forms and their Java equivalents[275]

OperationClojure formsJava equivalents

Create a new instance of a class ClassName

(ClassName.) (ClassName. arg1 arg2 …)

new ClassName() new ClassName(arg1, arg2, …)

Invoke an instance method on an object

(.methodName object) (.methodName object arg1 arg2 …)

object.methodName() object.methodName(arg1, arg2, …)

Invoke the a static method staticMethod in a class ClassName

(ClassName/staticMethod) (ClassName/staticMethod arg1 arg2 …)

ClassName.staticMethod() ClassName.staticMethod(arg1, arg2, …)

Access the value of a static field FIELD in a class ClassName

ClassName/FIELD

ClassName.FIELD

Refer to a Class

ClassName

ClassName.class

Access the value of an instance field field in an object object

(.field object)

object.field

Set the value of an instance field field in an object object to 5

(set! (.fieldName object) 5)

object.fieldName = 5

[275] We’re fibbing just a little here: There are actually only two fundamental host interop forms, . (a period) and new. The former provides method invocation and field access whereas the latter provides constructor invocation. Except for set!, all the forms above are expanded into various usages of . and new. This syntactic sugar is explained ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required