Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Calling Clojure from Java

DZone's Guide to

Calling Clojure from Java

· Java Zone
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

Calling Clojure from Java is easy, if you know which classes are important. On my current project I make all my Clojure files resources, load them, and call the functions directly. The following example shows Clojure printing the argument it's given.

; printer.clj
(ns printer)

(defn print-string [arg]
(println arg))

// Java calling code
RT.loadResourceScript("printer.clj");
RT.var("printer", "print-string").invoke("hello world");


There's a few things worth noting about the example: RT.var takes the namespace name and the function name. The Var returned by RT.var has an invoke method that allows you to pass any number of Objects. The invoke method also returns an Object, which allows you return values from Clojure where necessary.

It's also worth noting that the Clojure/Java interop is very, very good. You could pass a Java object to Clojure, make changes to it in Clojure, and return it back to Java. Of course, you might not even need to return it to Java since the instance referenced in Clojure would be the same instance referenced in Java.

From http://blog.jayfields.com/

Download Modern Java EE Design Patterns: Building Scalable Architecture for Sustainable Enterprise Development.  Brought to you in partnership with Red Hat

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}