Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)
Most of the top google hits for "calling clojure from java" are outdated and recommend using clojure.lang.RT to compile the source code. Could you help with a clear explanation of how to call Clojure from Java assuming you have already built a jar from the Clojure project and included it in the classpath?

1 Answer

0 votes
by (46k points)

This answer was written in 2010, and worked at that time. See Alex Miller's answer for more modern solution.

What kind of code are calling from Java? If you have class generated with gen-class, then simply call it.

If you want to evaluate code from string, inside Java, then you can use following code:

import clojure.lang.RT;

import clojure.lang.Var;

import clojure.lang.Compiler;

import java.io.StringReader;

public class Foo {

  public static void main(String[] args) throws Exception {

    // Load the Clojure script -- as a side effect this initializes the runtime.

    String str = "(ns user) (defn foo [a b] (str a \" \" b))";

    //RT.loadResourceScript("foo.clj");

    Compiler.load(new StringReader(str));

    // Get a reference to the foo function.

    Var foo = RT.var("user", "foo");

    // Call it!

    Object result = foo.invoke("Hi", "there");

    System.out.println(result);

  }

}

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...