liveBook · Manning

Accessor method

As explained in Clojure: The Essential Reference

Getter and setter methods are methods that respectively read and modify an object's exposed property values.

An accessor method exposes an object’s property through a method call. A getter reads a value; a setter changes it. This is useful when a field is not public but callers still need a defined way to read or update it. Under JavaBean conventions, attributes are private and accessible through getters and setters. section 15.4 section 21.5

Expose mutable fields from a Clojure type

(definterface IPerson (getName []) (setName [s]) (getAge []) (setAge [n])) (deftype Person [^:unsynchronized-mutable name ^:unsynchronized-mutable age] IPerson (getName [this] name) (setName [this s] (set! name s)) (getAge [this] age) (setAge [this n] (set! age n))) (def p (->Person "Natasha" "823")) (.getAge p) ;=> "823" (.setAge p 23) ;=> 23 (.getAge p) ;=> 23 The interface names the available calls. The getters return field values; the setters use `set!` to change them. Mutable fields require explicit synchronization if instances are accessed concurrently. section 15.4

Accessors need not be setters. For a Clojure struct, `(accessor waypoint :id)` creates a one-argument function that reads `:id` from a struct instance; it does not modify the struct. This differs from the getter–setter pair used to expose a mutable `deftype` field. section 11.1.4 section 15.4

For Java bean-like objects, Clojure’s `bean` turns discoverable properties into a map, so callers can inspect exposed values without calling each getter individually. It uses substantial reflection: for speed-critical code, direct getter calls and a purpose-built map can be much faster. section 21.5

How Clojure: The Essential Reference covers it

How deep it goes
Shows complete getter and setter implementations with `deftype`, then discusses JavaBean conventions and reflective property conversion.
Examples
Demonstrates age getters and setters on a mutable type, struct-key lookup, and conversion of a Java point to a map.
What you can do after
Build it from scratch with `definterface` and `deftype` to expose a mutable field through getter and setter methods.
How it connects
Connects accessor methods to `definterface`, `deftype`, JavaBeans, `bean`, and Clojure struct accessors.

Also explained in

Compare how 13 books explain accessor method →

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.