Last active
January 8, 2016 12:11
-
-
Save jstaffans/747504f0150c8ada0e1d to your computer and use it in GitHub Desktop.
Clojure and Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns example-app.core) | |
(defn send-mails | |
[{:keys [weather-forecast]}] | |
;; ... | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For testing purposes, the interface can be stubbed: