简体   繁体   中英

clojure gen-class generated classes invocation issue

I defined the following 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.

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. 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):

(Date.)
(DateFormat.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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