Clojure: Call Java Method
Create Java Object
(new classname arg1 arg2 …)
- Return a Java object of class classname, with its args feed to its constructor. 〔see Java Tutorial: Constructor〕
;; creating Java string object from Clojure (new String) ;; creating Java java.util.Date object from Clojure (new java.util.Date)
Another way to create a object is by this syntax:
(class_name. arg1 arg2 …)
Note the period immediately following the class name.
example:
;; creating Java string object from Clojure (new String) ; ⇒ "" ;; equivalent to (String.)
;; creating Java java.util.Date object from Clojure (new java.util.Date) ; #inst "2014-11-19T21:06:03.072-00:00" ;; equivalent to (java.util.Date.)
Call Java Instance Method/Field
To call a Java instance method, use this syntax:
(. object_name method_name args)
-
is Java's
object_name.method_name(args)
It is also equivalent to:
(.method_name object_name args)
example:
;; 2 ways to call Java's string method named codePointAt (.codePointAt "abc" 0) ; 97 (. "abc" codePointAt 0) ; 97 ;; the unicode codepoint for character a is 97clojure.core/.
Call Java Static Method/Field
To call a static method, or get value of a static field, you can use the syntax:
(class_name/method_name args)
example:
;; call Java static method named floor in class Math (Math/floor 1.7) ; ⇒ 1.0
〔see Java: static〕
Set Java Instance Field
(set! var-symbol expr)
(set! (. instance-expr instanceFieldName-symbol) expr)
(set! (. Classname-symbol staticFieldName-symbol) expr)
Used to set thread-local-bound vars, Java object instance fields, and Java class static fields.
Java Basics
For review of Java Basics, see: