跳轉到內容

學習 Clojure/呼叫 Java

來自華夏公益教科書,一個開放的世界中的開放書籍
  • (. 例項方法引數*)
  • (. 類方法引數*)

特殊形式 . 也稱為 宿主,呼叫公共 Java 方法或檢索公共 Java 欄位的值

(. foo bar 7 4)   ; call the method bar of the instance/class foo with arguments 7 and 4
(. alice bob)     ; return the value of public field bob of the instance/class alice

請注意,訪問欄位可能會被誤認為是呼叫無引數方法:如果一個類具有無引數方法和同名的公共欄位,則透過假設呼叫方法是預期的來解決歧義。

如果 . 的第一個引數是符號,則符號將以特殊方式求值:如果符號解析為當前名稱空間中引用的類,則這是對該類的靜態方法之一的呼叫;否則,這是對從符號解析的例項的方法的呼叫。因此,令人困惑的是,將 . 與未引用的符號一起使用來解析為類,是對該類物件的例項方法的呼叫,而不是對該類物件所代表的類的靜態方法的呼叫

(. String valueOf \c)   ; invoke the static method String.valueOf(char) with argument 'c'
(def ned String)        ; interned Var mapped to ned now holds the Class of String
(. ned valueOf \c)      ; exception: attempt to call Class.valueOf, which doesn't exist

雖然 . 運算子是訪問 java 的通用運算子,但存在更易讀的閱讀器宏,應優先使用它們而不是直接使用 .

  • (.欄位例項引數*)
  • 類/靜態欄位(類/靜態方法引數*)

注意:在 Subversion 修訂版 1158 之前,.field 也可用於靜態訪問。但是,在最近版本的 Clojure 中,(.field 類名) 形式將被視為 類名 是類 java.lang.Class 的相應例項。

因此,上面的示例將寫成

(String/valueOf \c)    ; Static method access!
(def ned String)
(.valueOf ned \c)      ; This will fail
(.valueOf String \c)   ; And in recent versions, so will this.

如果有必要操作類物件,例如呼叫 Class.newInstance 方法,可以執行以下操作

(. (identity String) newInstance "fred")   ; will create a new instance; this will work in all versions of clojure
(.newInstance String "fred")               ; will work only in a recent enough version of clojure. Expands to the above form.
(.newInstance (identity String) "fred")    ; this was required in old versions


  • (new 類引數*)

特殊形式 new 例項化 Java 類,使用提供的引數呼叫其建構函式

(new Integer 3)    ; instantiate Integer, passing 3 as argument to the constructor

與使用 . 呼叫靜態方法一樣,類必須指定為符號,而不是您想要例項化的類的類物件

(new String "yo")   ; new String("yo")
(def ned String)    ; interned Var mapped to ned now holds the Class of String
(new ned "yo")      ; exception: new Class("yo") is invalid

也存在用於 new 的閱讀器宏

  • (類名. 引數*)
(String. "yo")      ; equivalent to (new String "yo"). Notice the dot!
Previous page
分支和單子
學習 Clojure Next page
構建 Jars
呼叫 Java
華夏公益教科書