Clojure使用重载方法来重新定义Java接口

时间:2014-01-08 15:48:17

标签: clojure clojure-java-interop

我正在尝试在Clojure中实现以下Java接口:

package quickfix;

public interface MessageFactory {
    Message create(String beginString, String msgType);
    Group create(String beginString, String msgType, int correspondingFieldID);
}

以下Clojure代码是我尝试这样做的:

(defn -create-message-factory 
  []
  (reify quickfix.MessageFactory
    (create [beginString msgType]
      nil)
    (create [beginString msgType correspondingFieldID]
      nil)))

无法使用错误进行编译:

  

java.lang.IllegalArgumentException:无法在接口中定义方法:create

documentation建议重载的接口方法没问题,只要arity不同,就像在这种情况下一样:

  

如果方法在协议/接口中过载,则为多个   必须提供独立的方法定义。如果超负荷   在界面中相同的arity,您必须指定完整的提示   消除歧义 - 缺少提示意味着对象。

我怎样才能使这个工作?

1 个答案:

答案 0 :(得分:7)

您错过了参数。 reify实现的每个方法的第一个参数是对象本身(与defrecord / deftype一样)。所以,试试这个:

(defn -create-message-factory 
  []
  (reify quickfix.MessageFactory
    (create [this beginString msgType]
      nil)
    (create [this beginString msgType correspondingFieldID]
      nil)))
相关问题