How do I implement a Java interface in Clojure

后端 未结 5 739
隐瞒了意图╮
隐瞒了意图╮ 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:22

    As of Clojure 1.6, the preferred approach would be as follows. Assuming you have, on your classpath, the Clojure 1.6 jar and the following clojure file (or its compiled equivalent):

    (ns my.clojure.namespace
      (:import [my.java.package Doer]))
    
    (defn reify-doer
      "Some docstring about what this specific implementation of Doer
      does differently than the other ones. For example, this one does
      not actually do anything but print the given string to stdout."
      []
      (reify
        Doer
        (doSomethin [this in] (println in))))
    

    then, from Java, you could access it as follows:

    package my.other.java.package.or.maybe.the.same.one;
    
    import my.java.package.Doer;
    import clojure.lang.IFn;
    import clojure.java.api.Clojure;
    
    public class ClojureDoerUser {
        // First, we need to instruct the JVM to compile/load our
        // Clojure namespace. This should, obviously, only be done once.
        static {
            IFn require = Clojure.var("clojure.core", "require");
            require.invoke(Clojure.read("my.clojure.namespace"));
            // Clojure.var() does a somewhat expensive lookup; if we had more than
            // one Clojure namespace to load, so as a general rule its result should
            // always be saved into a variable.
            // The call to Clojure.read is necessary because require expects a Clojure
            // Symbol, for which there is no more direct official Clojure API.
        }
    
        // We can now lookup the function we want from our Clojure namespace.
        private static IFn doerFactory = Clojure.var("my.clojure.namespace", "reify-doer");
    
        // Optionally, we can wrap the doerFactory IFn into a Java wrapper,
        // to isolate the rest of the code from our Clojure dependency.
        // And from the need to typecast, as IFn.invoke() returns Object.
        public static Doer createDoer() {
            return (Doer) doerFactory.invoke();
        }
        public static void main(String[] args) {
            Doer doer = (Doer) doerFactory.invoke();
            doer.doSomethin("hello, world");
        }
    }
    

提交回复
热议问题