2016-07-25 100 views
2

我有很简单的Java代码重写类:作出这样的延伸类Clojure中

public class MessageListenerExample extends ListenerAdapter 
{ 
    @Override 
    public void onMessageReceived(MessageReceivedEvent event) 
    { 
     // do something with event 
    } 
} 

不过,我似乎无法理解如何把代码变成Clojure的代码。文档和文章非常混乱。我很乐意看到更多的例子。我也有兴趣使用implements

回答

3

取决于你需要做什么,有几个选项:

  1. 如果你真的需要延长 Clojure中的一个类(不是对象等),那么你可以使用创一流做到这一点,见https://clojuredocs.org/clojure.core/gen-class。最好使用NS宏,像
(ns your.class.Name 
    :extends whatever.needs.to.be.Extended) 

(defn -methodYouOverride ; mind the dash - it's important 
    [...] ...) 

我不会推荐下去,除非绝对必要的这条道路。正确编译(包括AOT编译)是非常棘手的。最后,您仍然需要使用Java interop来处理这个类的对象,所以不确定它是否值得这样麻烦,这使我可以:

  1. 将它编码Java并使用Java interop来处理它。

  2. 如果你确实需要创建一个对象,器具某个接口,那么它更容易的一个实例:

(reify 
    InterfaceYouImplement 
    (methodYouImplement [..] ..) 

我用它在我的代码,它的真多在Java中编码更好。

1

只是自己实现EventListener,而不是使用那里的适配器类来为java程序员提供更方便的东西(但是让clojure程序员更难!)。您将收到一个Event对象,并且您可以检查它是否是MessageReceivedEvent的实例,就像适配器would do for you一样。

在Clojure中实现接口是通过reify完成的 - 例如参见https://stackoverflow.com/a/8615002/625403

2

您可以使用proxy来扩展现有的Java类并实现接口。例如:

(import '[java.awt.event ActionListener ActionEvent KeyAdapter KeyEvent]) 

(def listener 
    (proxy 
    ;; first vector contains superclass and interfaces that the created class should extend/implement 
    [KeyAdapter ActionListener] 
    ;; second vector contains arguments to superclass constructor 
    [] 
    ;; below are all overriden/implemented methods 
    (keyPressed [event] 
     (println "Key pressed" event)) 
    (actionPerformed [action] 
     (println "Action performed" action)))) 

(.keyPressed listener nil) 
;; => Key pressed nil 

(.actionPerformed listener nil) 
;; => Action performed nil