如何使java API包装器与不同的功能arities一起工作?

时间:2013-04-28 01:42:18

标签: clojure arity

我正在为Java API编写一个小包装器,我创建了一个像这样的监听器

(defn conv-listener [f]
  (proxy [com.tulskiy.keymaster.common.HotKeyListener] [] (onHotKey [hotKey] (f))))

无论函数f是接受1还是零参数,我都可以使用它。 (即如果f不接受参数,只需用(f)调用它,如果它接受一个参数 - 在这种情况下将是热键的值 - 用(f hotKey)调用它)?

2 个答案:

答案 0 :(得分:4)

没有。只需要一直调用(f hotKey),如果有人想使用忽略hotKey的函数,那么他们就可以传递(fn [_] (...do whatever...))之类的内容。

答案 1 :(得分:1)

这就是我们最终解决的问题(来自Nic Marsh的请求):

(defn arg-count [function]
  "Counts the number of arguments the given function accepts"
  (let [method     (first (.getDeclaredMethods (class function)))
        parameters (.getParameterTypes method)]
    (alength parameters)))

(defn call-with-correct-args [function & args]
  "Call the given function on all given args that it can accept"
  (let [amount-accepted (arg-count function)
        accepted-args   (take amount-accepted args)]
    (apply function accepted-args)))

(defn- conv-listener [function]
  "Takes a function with one argument, which will get passed the keycode, and creates a listener"
  (proxy [com.tulskiy.keymaster.common.HotKeyListener] []
    (onHotKey [hotKey] (call-with-correct-args function hotKey))))

http://github.com/houshuang/keymaster-clj