2013-04-28 86 views
2

我写的Java API小包装,并创建一个侦听器这样如何让java API包装器与不同的函数库一起工作?

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

有没有一种方式,我可以使这个工作中的作用f是否接受1个或零参数。 (也就是说,如果f不接受参数,只要调用(f),如果它接受一个参数 - 在这种情况下这将是热键的值 - 用(f hotKey)调用它)?

+0

可能的欺骗:http://stackoverflow.com/questions/10769005/functions-overloaded- with-different-number-of-arguments – noahlz 2013-04-28 02:18:46

+1

这不是一个重复的问题,甚至与此相关。 – amalloy 2013-04-28 03:09:38

+0

好的。误解。 – noahlz 2013-04-28 11:47:19

回答

4

编号只需拨打(f hotKey),如果有人想使用忽略hotKey的函数,那么他们只能通过(fn [_] (...do whatever...))之类的东西。

1

这就是我们最终解决它(从尼克沼泽拉请求):

(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

相关问题