5

我正在尝试从 JGroups 使用reify.

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) {}
        }
    }
}

在这种情况下,接收方法出现了两次,每次都有一个参数(当然还有不同的类型)。当我尝试reify在 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界面中绝对可用的那样,我认为此问题与重载方法有关,并且我的 typ 提示不起作用。我究竟做错了什么?

编辑:根据 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)
4

1 回答 1

8

当您添加缺少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
于 2017-02-27T10:45:10.050 回答