1

Hello I have a main method in a Java class and I would like to access and run my clojure functions from my java classes, is that possible right?

Help please

2
  • I think you're mis-spelling something 'clojure'. Don't get it though, I say 'Yes'. Commented Oct 5, 2011 at 13:06
  • 1
    clojure is a JVM scripting language (Lisp like). Commented Oct 5, 2011 at 13:11

4 Answers 4

4

If you just want to call a function which you have defined in a Clojure script the following code might help you getting the job done:

test.clj:

(ns test)
(defn hello [name]
  (println (str "Hi " name "!")))

TestRun.java:

import clojure.lang.RT;
public class TestRun {
    public static void main(String[] args) throws Exception {
        RT.loadResourceScript("test.clj");
        // var(namespace, function name).invoke(parameters..)
        RT.var("test", "hello").invoke("Daisy Duck");
    }
}

Output:

Hi Daisy Duck!

Make sure you have the Clojure jar on your classpath

Sign up to request clarification or add additional context in comments.

2 Comments

In 2008 before clojure had ahead of time compilation this was the answer. It is terribly innefficient today. the correct answer is to compile a class with methods and call them from java as you would anything else. no need to compile at every run
Yep, you're certainly right. I prefer to optimize when speed becomes an issue ;)
2

Do you have your Clojure code compiled and packaged in a jar? Do you have the jar in your classpath? If so, you should be able to use the classes in the jar just as if there were written in Java.

Comments

2

see the accepted answer to this question: Calling clojure from java

in short you add the mothods you want to expose to your namespace:

(ns com.domain.tiny
  (:gen-class
    :name com.domain.tiny
    :methods [ [binomial [int int] double]]))

then write the functions. compile your class file with maven/leiningen

then call them from java:

System.out.println("(binomial 5 3): " + tiny.binomial(5, 3));

This is just an excerpt. take a look as the origional question.

Comments

0

Check the Java Scripting API for calling functions in script files: http://download.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.