Skip to content

Instantly share code, notes, and snippets.

@jstaffans
Last active January 8, 2016 12:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jstaffans/747504f0150c8ada0e1d to your computer and use it in GitHub Desktop.
Save jstaffans/747504f0150c8ada0e1d to your computer and use it in GitHub Desktop.
Clojure and Java
(ns example-app.core)
(defn send-mails
[{:keys [weather-forecast]}]
;; ...
)
(ns example-app.interop
(:require [example-app.core :as core])
;; This is an example of how to integrate a separately built Clojure library as a JAR file
;; in a Java application. We imagine an application where the Clojure library is responsible
;; for sending out mails based on weather forecasts, and the Java application is providing
;; the actual forecast. We therefore consider two-way communication:
;; - the Clojure library needs to call some methods of the wrapping Java application
;; to do its work. For this we supply an interface that the Java application can implement.
;; - The Java application needs to call the Clojure library, maybe as a response to an
;; event or as a scheduled service. For this case, we provide a class that the Java application
;; can instantiate.
;; This namespace needs to be AOT'd.
;; The interface that the java app can implement
(gen-interface
:name com.example.WeatherForecast
:methods [[getTemperature [] Double]])
;; The class that the java app instantiates
(gen-class
:name com.example.HighTemperatureMailer
:state state
:init init
;; Dependency Injection - take an instance of the previously defined interface as a constructor argument
:constructors {[com.example.WeatherForecast] []}
:methods [[sendMails [] void]])
(defn -init [weather-forecast]
[[] {:weather-forecast weather-forecast}])
;; The actual work is done in the core namespace
(defn -sendMails
[this]
(core/send-mails (.state this)))
@jstaffans
Copy link
Author

For testing purposes, the interface can be stubbed:

(core/send-mails (reify com.example.WeatherForecast (getTemperature [this] ...)))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment