Clojure: How to find out the arity of function at runtime?

前端 未结 7 1408
野趣味
野趣味 2021-01-31 02:08

Given a function object or name, how can I determine its arity? Something like (arity func-name) .

I hope there is a way, since arity is pretty central in C

7条回答
  •  后悔当初
    2021-01-31 02:41

    My take at the arity problem, building on the other solutions:

    (defn arity
     "Returns the maximum parameter count of each invoke method found by refletion
      on the input instance. The returned value can be then interpreted as the arity
      of the input function. The count does NOT detect variadic functions."
      [f]
      (let [invokes (filter #(= "invoke" (.getName %1)) (.getDeclaredMethods (class f)))]
      (apply max (map #(alength (.getParameterTypes %1)) invokes))))
    

提交回复
热议问题