简体   繁体   English

clojure gen-class生成的类调用问题

[英]clojure gen-class generated classes invocation issue

I defined the following MyCache.clj 我定义了以下MyCache.clj

(ns abcd.MyCache
  (:gen-class
   :name "abcd.MyCache"
   :init "init"
   :constructors { [java.text.DateFormat][] }
   :methods [ [now [] void] [myformat [long] String] ]
   :state "state"
   :main false))

(defn -init[format]
  ([[] (atom {:format format})]))



(defn -now[this] ( (:format @(.state this)) (System/currentTimeMillis)))

(defn -myformat[this time]
    ( (:format @(.state this) (new java.util.Date time))))

I compiled the above file using (compile 'abcd.MyCache) successfully. 我使用(compile'abcd.MyCache)成功地编译了以上文件。

When I am trying to use the generated classes as shown below..I am getting errors. 当我尝试使用如下所示的生成的类时。 Please help. 请帮忙。

user=> (new abcd.MyCache (new java.text.SimpleDateFormat "mmDDyyyy"))
IllegalArgumentException Key must be integer  clojure.lang.APersistentVector.invoke (APersistentVector.java:265)

I don't feel well about this: 我对此感到不舒服:

(defn -init[format]
  ([] [atom {:format format}]))

You are trying to get an element from a vector and it is expects an index (number). 您正在尝试从向量中获取元素,并且期望有一个索引(数字)。

What is correct is to deref the atom and get its value as the index of the vector. 正确的方法是对原子进行反引用,并获取其值作为矢量的索引。 But again in your case, you are trying to query an empty vector. 但是,在这种情况下,您还是要查询一个空向量。

Notice also, that [atom {:format format}] isn't the correct way to create an atom. 还要注意,[atom {:format format}]不是创建原子的正确方法。 You should use: 您应该使用:

(atom {:format format})

And by the way, the following form is the preferred one to create Java objects (nothing wrong with (new) of course): 顺便说一句,以下形式是创建Java对象的首选形式(当然,(新)没错):

(Date.)
(DateFormat.)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM