我有一个值 vector ,例如 [210 50 60]
,我需要用它创建 Java 对象。例如我想创建 Color
:
(Color. 210 50 60) ; standard way
(apply Color. [210 50 60]) ; hmm... I need something like this
当然 Color.
不是一个函数,我们不能对它使用 apply
。有没有一种优雅的方法来解决这个任务,还是我必须这样写:
(let [[r g b] [210 50 60]]
(Color. r g b))
最佳答案
如果您不介意支付反射成本,我认为 https://stackoverflow.com/a/9172515/151650是一种优雅的方式。 如果你不介意疯狂的宏:
(defn arity [c i]
(let [args (map #(symbol (str "arg" %)) (range i))]
`([~@args] (new ~c ~@args))))
(defmacro ->c [c]
(let [cs (.getConstructors (resolve c))
arities (set (map #(count (.getParameterTypes %)) cs))
fn-arities (map #(arity c %) arities)]
`(fn ~@fn-arities)))
(apply (->c java.awt.Color) 1 [2 3])
关于java - 申请Java构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26212769/