Java: How to implement the interface?

How do I implement a Java interface in Clojure

  • How do I create a Clojure object that implements this interface and then gets called from Java code? public interface Doer { public String doSomethin(String input); } Doer clojureDoer = ?; String output = clojureDoer.doSomethin(input);

  • Answer:

    With proxy See the proxy macro. http://clojuredocs.org/clojure_core/clojure.core/proxy have some examples. It's also covered on http://clojure.org/java_interop#Java%20Interop-Implementing%20Interfaces%20and%20Extending%20Classes 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 https://stackoverflow.com/questions/2181774/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

iradik at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

reify is strongly preferred for implementing interfaces - proxy is heavy-duty, old, and slow, so should be avoided when possible. An implementation would look like: (reify Door (doSomethin [this input] (...whatever...))) Note that the existing answer about using proxy has incorrect syntax, if you decide to go with a proxy after all: proxy takes an implicit this argument, not a named first argument.

amalloy

For a more general take on this question, this diagram can be freaking useful when you are in need for some kind of Java-interop: https://github.com/cemerick/clojure-type-selection-flowchart

Michiel Borkent

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.