Education‎ > ‎Closer to Clojure‎ > ‎

Closer to Clojure 07: Java

You can access to Java classes. Let's try pow method of java.lang.Math class for example. (You can omit java.lang as you can in Jana.)

user=> (. Math pow 2 4)
16.0
user=> (Math/pow 2 4)
16.0

You can even omit the package name by import. The following code does the same thing as (. java.util.Calendar APRIL). (The result is 3.)

(import '(java.util Calendar GregorianCalendar))
(. Calendar APIRL) ; or Calendar/APRIL

You can call constructor in the two different ways.

(import '(java.util Calendar GregorianCalendar))
(def calendar (new GregorianCalendar 2008 Calendar/APRIL 16))
(def calendar (GregorianCalendar. 2008 Calendar/APRIL 16))

Method call is done by the following syntax.

(. calendar add Calendar/MONTH 2)
(.add calendar Calendar/MONTH 2)

Reference:
http://java.ociweb.com/mark/clojure/article.html
Javaクラスへのアクセスが可能です.java.lang.Math クラスのpowメソッドを呼び出してみましょう.(Javaと同じくパッケージ名 java.lang は省略できます.)

user=> (. Math pow 2 4)
16.0
user=> (Math/pow 2 4)
16.0

importを使えばパッケージ名を省略できます.以下の例は (. java.util.Calendar APRIL) と同じことをするコードです.(結果は3です.)

(import '(java.util Calendar GregorianCalendar))
(. Calendar APIRL) ; or Calendar/APRIL

コンストラクタは次の二通りの方法で呼び出せます.

(import '(java.util Calendar GregorianCalendar))
(def calendar (new GregorianCalendar 2008 Calendar/APRIL 16))
(def calendar (GregorianCalendar. 2008 Calendar/APRIL 16))

メソッド呼び出しは次のようにします.

(. calendar add Calendar/MONTH 2)
(.add calendar Calendar/MONTH 2)

参考
http://java.ociweb.com/mark/clojure/article.html
Comments