没有使用 reify 与 Clojure Java 互操作的匹配方法

No matching method with Clojure Java interop using reify

我对某个Clojure/Java互操作有误解。

我正在使用 Pi4J 库,我想在 GPIO 引脚上获得一个监听器。

用法文档:https://pi4j.com/1.2/usage.html(在"Listen for Pin Changes"下)给出了以下示例:

public static class GpioUsageExampleListener implements GpioPinListenerDigital {
    @Override
    public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
        // display pin state on console
        System.out.println(" --> GPIO PIN STATE CHANGE: " + event.getPin() + " = "
                + event.getState());
    }
}

// create and register gpio pin listener
myButton.addListener(new GpioUsageExampleListener());

还有一个示例应用程序:https://pi4j.com/1.2/example/listener.html

其中有:

myButton.addListener(new GpioPinListenerDigital() {
    @Override
    public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
        // display pin state on console
        System.out.println(" --> GPIO PIN STATE CHANGE: " + event.getPin() + " = " + event.getState());
    }
});

所以,我正在尝试以下 Clojure 代码:

(import [com.pi4j.io.gpio GpioFactory GpioPinDigitalInput PinPullResistance RaspiPin]
        [com.pi4j.io.gpio.event GpioPinListenerDigital])

(def gpio (GpioFactory/getInstance))
(def mybutton (.provisionDigitalInputPin gpio RaspiPin/GPIO_02 PinPullResistance/PULL_DOWN))

(def gpio-listener (reify GpioPinListenerDigital
                    (handleGpioPinDigitalStateChangeEvent [this event]
                      (println "GPIO Event Occured"))))

(.addListener mybutton gpio-listener)

但我得到:

No matching method addListener found taking 1 args for class com.pi4j.io.gpio.impl.GpioPinImpl

使用反射,我查看了 mybutton 实例可用的方法,我可以看到方法就在那里:

(clojure.reflect/reflect mybutton)

 :members
 #{{ 
    ;;; Stuff trimmed
   {:name addListener,
    :return-type void,
    :declaring-class com.pi4j.io.gpio.impl.GpioPinImpl,
    :parameter-types [java.util.List],
    :exception-types [],
    :flags #{:public :synchronized}}
   {:name addListener,
    :return-type void,
    :declaring-class com.pi4j.io.gpio.impl.GpioPinImpl,
    :parameter-types [com.pi4j.io.gpio.event.GpioPinListener<>],
    :exception-types [],
    :flags #{:varargs :public :synchronized}}}}

我已经成功地检查了 gpio-listener 与 GpioPinListener 的类型。

(cast com.pi4j.io.gpio.event.GpioPinListener gpio-listener)
#object[user$reify__7404 0x11251bd "user$reify__7404@11251bd"]

我尝试将参数类型提示给 GpioPinListener,但我得到了相同的结果。

我对 Clojure 和 Java 知识的缺乏让我在这里失败了,所以我有点迷失了下一步要看的地方,但我确信这是非常基础的东西。

我无法对此进行测试,但如果您注意到 the docs, you'll see that addListener is actually var-arg, and dealing with var-arg methods can be confusing due to misunderstandings of how var-arg methods in Java work

addListener 期待 array 听众(由 Java var-arg 语法加糖)。尝试

(.addListener mybutton
              (into-array [gpio-listener])) 

或者,由于 addListener 实际上有一个 List 过载,这也可能有效

(.addListener myButton [gpio-listener])