[英]How do I set up classes in a Lein project?
我運行了lein new app hm
,然后在hm/src/hm
core.clj
編輯為:
(ns hm.core
(:gen-class)
(:use [hm.hashmap]))
(defn -main []
(def j (new hm.hashmap))
(-add j "foo" "bar")
(println j))
和hashmap.clj
為:
(ns hm.hashmap
(:gen-class
:methods [[hashmap [] java.util.HashMap]
[add [String String]]]))
(defn -hashmap []
(def h (new java.util.HashMap))
h)
(defn -add [this key value]
(. this put key value)
this)
目的是圍繞HashMap進行包裝,以便我了解Clojure及其與Java的關系。 我對Clojure很陌生。 但是,當我對此進行編譯時,在hashmap.clj
得到了很多ClassNotFoundException。 我該如何進行這項工作?
注意:這是您問題的直接答案。 我不建議您這樣學習Clojure。
您需要先編譯類,然后才能運行它們。 在您的project.clj中,將此添加到地圖中:
:aot [hm.hashmap]
然后,您需要運行lein compile
才能編譯類。 您應該看到輸出說hm.hashmap
類已編譯。 該運行后lein run
調用中的“主要”功能hm.core
。
我刪除了gen-class的:methods
部分,因為您已經在下面定義它們了,這導致了奇怪的java.lang.,
錯誤。 您將遇到其他錯誤,但這足以使您通過此問題。
您的代碼還有其他問題,但是直接的問題是add
的簽名不完整。 你add
回到this
,一個hm.hashmap
。
要解決此問題,請更改簽名以返回Object
,或者進行其他編輯以返回java.util.HashMap
。 如果您希望此方法以其他方式工作,則還需要擴展而不是封裝。
(ns hm.hashmap
(:gen-class
:extends java.util.HashMap
:methods [[add [String String] java.util.HashMap]]))
最后改變-main
在core.clj
使用要調用的方法.add
,而不是試圖訪問私有-add
。
...
(.add j "foo" "bar")
...
然后
lein clean
lein compile hm.core hm.hashmap
lein run
應該打印
#<hashmap {foo=bar}>
請注意,據我所知,由於符號解析的時間安排,您不能指定在簽名中返回hm.hashmap
。 請參閱GC問題81:當class返回self時,編譯gen-class失敗 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.