2016-07-25 58 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