Mark Engelberg <mark.engelb...@gmail.com> writes:

> Are there any examples available of creating a compiled
> class/interface with deftype and defprotocol, and using these from
> Java?

It's pretty straightforward and works exactly how you might expect it
to.

Create a new project:

   $ lein new interop

Define a type and protocol in interop/src/interop/core.clj:

    (ns interop.core)

    (defprotocol Vocal
      (dance [this boogie])
      (speak [this]))

    (deftype Chorus [noise]
      Vocal
      (dance [this boogie] (println "Shuffle like a" boogie))
      (speak [this] (println "I say there!  I can hear a" noise)))

    (println "boom") ;; just curious if this will be executed

Mark the namespace to be AOT-compiled by lein in interop/project.clj:

    (defproject interop "1.0.0"
      :aot [interop.core]
      :dependencies [[org.clojure/clojure "1.2.0"]])

Compile it:

    $ lein compile

Create a Java client class interop/src/Client.java:

    import interop.core.Chorus;
    import interop.core.Vocal;

    public class Client {
        public static void main(String args[]) {
            Vocal voice = new Chorus("bird");
            voice.speak();
            voice.dance("pigeon");
        }
    }

Compile it:

    $ javac -cp $(lein classpath) src/Client.java

Run it:

    $ java -cp $(lein classpath) Client
    I say there!  I can hear a bird
    Shuffle like a pigeon

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to