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

前端 未结 7 1411
野趣味
野趣味 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:28

    Sneaky reflection:

    (defn arg-count [f]
      (let [m (first (.getDeclaredMethods (class f)))
            p (.getParameterTypes m)]
        (alength p)))
    

    Or :

    (defn arg-count [f]
      {:pre [(instance? clojure.lang.AFunction f)]}
      (-> f class .getDeclaredMethods first .getParameterTypes alength))
    

提交回复
热议问题