2013-04-28 13 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

相關問題