Skip to content

Instantly share code, notes, and snippets.

@RichardHightower
Created April 6, 2016 19:54
Show Gist options
  • Save RichardHightower/3bf9a3fcccf9d0389aad5e97d082db11 to your computer and use it in GitHub Desktop.
Save RichardHightower/3bf9a3fcccf9d0389aad5e97d082db11 to your computer and use it in GitHub Desktop.
Example using Clojure from Java

Normal Java project

tree
.
├── build.gradle
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── java-clojure.iml
├── settings.gradle
└── src
    └── main
        ├── clojure
        │   └── io
        │       └── advantageous
        ├── java
        │   └── io
        │       └── advantageous
        │           └── clojureint
        │               ├── IHello.java
        │               └── Main.java
        └── resources
            └── io
                └── advantageous
                    └── clojureint
                        └── main.clj

IHello interface

package io.advantageous.clojureint;

public interface IHello {

    void sayHello(String name);
}

main.clj Defining instance of IHello in Clojure

(ns io.advantageous.clojureint
    (:require
        [clojure.pprint :as pprint]
    )
    (:import [io.advantageous.clojureint IHello])
    (:gen-class)
)

(defn hello "hello" [] (println "hello"))


(defn HelloClass
  "hello func"
  []
  (reify
    IHello
    (sayHello [this name] (println "hello " name))))

Invoking from Java. Main.java

package io.advantageous.clojureint;


import clojure.lang.IFn;
import clojure.java.api.Clojure;

public class Main {

    public static void main(final String... args) throws Exception {

        /* Import clojure core. */
        final IFn require = Clojure.var("clojure.core", "require");
        require.invoke(Clojure.read("io.advantageous.clojureint.main"));

        /* Invoke Clojure hello function. */
        final IFn helloFunc = Clojure.var("io.advantageous.clojureint", "hello");
        helloFunc.invoke();


        /* Create instance of IHello from Clojure "class" and use it */
        final IFn helloClass = Clojure.var("io.advantageous.clojureint", "HelloClass");
        final IHello helloInstance = (IHello) helloClass.invoke();

        helloInstance.sayHello("Justin");
    }

}

gradle build - nothing special

group 'io.advantageous'
version '1.0-SNAPSHOT'

apply plugin: 'java'

sourceCompatibility = 1.5

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
    compile 'org.clojure:clojure:1.8.0'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment