Skip to content

Java Integration

  • Clojure runs on JVM, therefore it has good integration with java
  • Access to java classes is faster when compared to clojure native functions
  • Java class: symbol with uppercase. E.g., Thread
  • Java static method: symbol with class/method. E.g., Thread/sleep
  • Java constructor method: symbol with class + dot. E.g., Thread.
  • Java instance method: dot + method E.g., .start (Thread. #())
; create and run a new thread
(def my-thread (Thread. #(println "i will run in a separate thread")))

; start thread
(.start my-thread)

; make the current thread sleep 4s
(Thread/sleep 4000)

Record (Java Class)

  • Represents a data structure (a schema)
  • A record definition works like a java class
  • A record instance works like a java object

  • The instance works similar to a hashmap

  • It allows expanding (more keywords) or shrinking (keywords nil)
(defrecord Person [id name age])

; constructor
(Person. 1 "Henry" 27) ; same
(->Person 1 "Henry" 27) ; same
(map->Person {:id 1, :name "Henry", :age 27}) ; same

Protocol (Java Interface)

  • Define functions that need to be implemented by a record that implements this protocol
  • To force a record to implement a protocol, you use the extend-type
;; Printable Interface
(defprotocol Printable
  (my-print-function) [arg1 arg2 arg3])

;; Person implements Printable
(defrecord Person [id name age])
(extend-type Person
  Printable ; interface to implement
  (my-print-function ; implementation of functions of that interface
    [person a b]
    (println "Person:" (:name person))))

;; Animal implements Printable
(defrecord Animal [id name age])
(extend-type Animal
  Printable ; interface to implement
  (my-print-function ; implementation of functions of that interface
    [animal a b]
    (println "Animal:" (:name animal))))

;; Instances
(let [p (->Person 1 "Henry" 27)]
  (my-print-function p "a" "b")) ; call the implementation of the Person class

(let [a (->Animal 2 "Doggy" 3)]
  (my-print-function a "a" "b")) ; call the implementation of the Animal class

Component (Java Object)

  • When you initialize a record you get a component