2

私はJava APIの小さなラッパーを書いていて、このようなリスナーを作成しています

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

f関数が1つまたは0の引数を受け入れるかどうかにかかわらず、これを機能させる方法はありますか? (つまり、fが引数を受け入れない場合は、 で呼び出します。引数を受け入れる場合は ((f)この場合はホットキーの値になります)、 で呼び出します(f hotKey))?

4

2 に答える 2

4

No. Just call (f hotKey) all the time, and if someone wants to use a function that ignores hotKey then they can just pass something like (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 に答える