2

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

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

f无论函数接受 1 个参数还是零个参数,有没有一种方法可以让我完成这项工作。(即,如果f不接受参数,只需用 调用它(f),如果它接受参数 - 在这种情况下将是热键的值 - 用 调用它(f hotKey))?

4

2 回答 2

4

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

于 2013-04-28T03:10:57.037 回答
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

于 2013-05-02T02:55:29.490 回答