如何使用重载方法来实现Java接口?

时间:2017-02-26 20:09:22

标签: clojure reify

我正在尝试实施'来自JGroups的以下Java接口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) {}
        }
    }
}

在这种情况下,接收方法存在两次,每个参数有一个参数(当然也有不同的类型)。当我在CIDER中使用以下代码尝试reify时:

(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)

1 个答案:

答案 0 :(得分:5)

当您添加缺少的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