gpt4 book ai didi

clojure - 如何用重载方法具体化Java接口(interface)?

转载 作者:行者123 更新时间:2023-12-02 11:22:45 56 4
gpt4 key购买 nike

我正在尝试使用 reify 从 JGroups“实现”以下 Java 接口(interface)。

public interface MessageListener extends StateListener {
/**
* Called when a message is received.
* @param msg
*/
void receive(Message msg);

/** Called when a batch of messages is received */
default void receive(MessageBatch batch) {
for(Message msg: batch) {
try {receive(msg);}
catch(Throwable t) {}
}
}
}

在这种情况下,接收方法出现两次,每个参数一个参数(当然,类型不同)。当我尝试在 CIDER 中使用以下代码具体化时:

(reify org.jgroups.MessageListener (receive[#^org.jgroups.Message msg] 
(println msg)))

我收到一条错误消息:

CompilerException java.lang.IllegalArgumentException: Can't define method not in interfaces: receive, compiling:(*cider-repl clj-groups*:49:21)

由于receive在界面中肯定可用,我认为这个问题与重载方法有关,并且我的打字提示不起作用。我做错了什么?

编辑:根据 Lees 注释更改代码后:

(reify org.jgroups.MessageListener (receive[this #^org.jgroups.Message msg]                                     
(println msg)))

错误消息已更改:

CompilerException java.lang.IllegalArgumentException: Mismatched return type: receive, expected: void, had: java.lang.Object, compiling:(*cider-repl clj-groups*:80:21)

最佳答案

当您添加缺少的 this 参数并提示返回和参数类型时,以下内容有效:

$ boot -d org.jgroups/jgroups:4.0.0.Final repl

(import '(org.jgroups MessageListener Message) '(org.jgroups.util MessageBatch))
;;=> org.jgroups.util.MessageBatch

(def listener
(reify MessageListener
(^void receive [this ^Message msg] (println "Message"))
(^void receive [this ^MessageBatch batch] (println "MessageBatch"))))
;;=> #'boot.user/listener

(.receive listener (Message.))
;; Message
;;=> nil

(.receive listener (MessageBatch. 0))
;; MessageBatch
;;=> nil

关于clojure - 如何用重载方法具体化Java接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42473644/

56 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com