How do I implement a Java interface in Clojure

后端 未结 5 728
隐瞒了意图╮
隐瞒了意图╮ 2020-12-05 14:53

How do I create a Clojure object that implements this interface and then gets called from Java code?

public interface Doer {
   public String doSomethin(Stri         


        
5条回答
  •  借酒劲吻你
    2020-12-05 15:06

    With proxy

    See the proxy macro. Clojure Docs have some examples. It's also covered on Java Interop page.

    (proxy [Doer] []
      (doSomethin [input]
        (str input " went through proxy")))
    

    proxy returns an object implementing Doer. Now, to access it in Java you have to use gen-class to make your Clojure code callable from Java. It's covered in an answer to the "Calling clojure from java" question.

    With gen-class

    (ns doer-clj
      (:gen-class
        :name DoerClj
        :implements [Doer]
        :methods [[doSomethin [String] String]]))
    
    (defn -doSomethin
      [_ input]
      (str input " went through Clojure"))
    

    Now save it as doer_clj.clj, mkdir classes and compile it by calling in your REPL (require 'doer-clj) (compile 'doer-clj). You should find DoerClj.class ready to be used from Java in classes directory

提交回复
热议问题