我正在为Java API编写一个小包装器,我创建了一个像这样的监听器
(defn conv-listener [f]
(proxy [com.tulskiy.keymaster.common.HotKeyListener] [] (onHotKey [hotKey] (f))))
无论函数f
是接受1还是零参数,我都可以使用它。 (即如果f
不接受参数,只需用(f)
调用它,如果它接受一个参数 - 在这种情况下将是热键的值 - 用(f hotKey)
调用它)?
答案 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))))