Sandwiching Clojure between Java with Leiningen

2019-05-02 10:13发布

问题:

For a class, I need to write some JVM code, and I'm hoping to use Clojure. I got it to work with the bottom part of the software stack, but I can't manage to make it work in between the GUI layer sitting on top and the bottom part. My main problem is getting the Java GUI to recognize my Clojure files. I want to use Leiningen for this, but the Java compiling solution doesn't seem to account for this interoperation. The answer here seems to be exactly what I need. I don't understand where to put the code and such (just not quite enough details). Does anyone have any tips?

I tried making a plugin, but it doesn't seem to work. I know my case is definitely on the fringe of problems, but a solution would make using Clojure in a classroom setting much easier.

Thanks!

MORE DETAILS:

I didn't have much luck with using a compiled Clojure jar. I need to create a (ugh) stateful Clojure class (i.e. the methods can't be static). The code for my class (src/final_project/MyLinkLayer.clj) looks like

(ns final_project.MyLinkLayer
  (:gen-class))

(defn -init[s] (print s))
(defn -send [dest data len] (println data))
(defn -recv [trans] (println trans))
(defn -status [] (println "I am a status!"))
(defn -command [cmd value] (println (str cmd " with value=" value)))

My project.clj is

(defproject final_project "0.1.0-SNAPSHOT"
  :description "A simulated MAC layer."
  :dependencies [[org.clojure/clojure "1.4.0"]
                 [local/classFiles "1"]]
  :aot [final_project.MyLinkLayer])

The class compiles ("lein compile") fine into "target/classes/final_project/", but the methods don't show up. I can load the class via jar (using Maven in the top Java part of my project imports of the package work well enough). I even checked the .class file with Eclipse, and the only methods generated are those from Object. Any thoughts? Also, once I actually get to the "stateful" part of my Clojure class, does anyone have any ideas? Thanks in advance.

回答1:

When I write projects that use both Clojure and Java, then I normally use Maven rather than Leiningen - for the simple reasons that most of the Java tools (e.g. Eclipse) understand Maven better than they understand Leiningen at present.

Here's an example pom.xml that I use for polyglot Clojure/Java projects:

  • https://github.com/mikera/clojure-pom/blob/master/pom.xml

Note the key features:

  • use of clojure-maven-plugin
  • configuration of the Clojure source directories to be considered as resources - this ensures the .clj files are treated as resources, are bundled in any .jar files produced and can be dynamically loaded at runtime (this might solve the problem you are seeing with Java failing to recognise your .clj files)
  • Inclusion of clojars.org as a repository - pretty much essential for serious Clojure development!