简体   繁体   中英

clojure gen-class varargs constructor

在:constructors映射和后续的-init定义中,如何表示varargs构造函数(假设超类具有多个构造函数,其中一个是varargs)?

Since varargs are essentially syntax sugar for Object arrays, you could just use "[Ljava.lang.Object;" as the type of constructor's parameter.

Here's some sample code:

(ns t.vtest
  (:gen-class
   :implements   [clojure.lang.IDeref]
   :init init
   :state state
   :constructors {["[Ljava.lang.Object;"] []}))
   ;;                                      ^-----------------------
   ;; You should put "[Ljava.lang.Object;" for superclass varargs constructor here
   ;; I left it blank for the sake of working example 

(defn -init
  [args]
  (println "first element of args" (aget args 0) "total elements" (alength args))
  [[] (into [] args)])

(defn -deref
  [this]
  (.state this))

and that's how it looks in REPL

user=> @(t.vtest. (into-array Object ["A" "B" 1 2]))
first element of args A total elements 4
["A" "B" 1 2]

Since clojure don't support it at the moment you need to patch it with: https://groups.google.com/forum/#!topic/clojure/HMpMavh0WxA.

And use it with new meta tag:

(ns t.vtest 
  (:gen-class 
   :implements   [clojure.lang.IDeref]
   :init init
   :state state
   :constructors {^:varargs ["[Ljava.lang.Object;"] []} 
  ))

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