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

Mridul Raj
  • 1,001
  • 4
  • 19
  • 46
andre
  • 329
  • 2
  • 12

4 Answers4

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

Matt
  • 17,290
  • 7
  • 57
  • 71
  • 1
    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 – Arthur Ulfeldt Oct 05 '11 at 18:08
  • Yep, you're certainly right. I prefer to optimize when speed becomes an issue ;) – Matt Oct 05 '11 at 22:58
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.

John B
  • 32,493
  • 6
  • 77
  • 98
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.

Community
  • 1
  • 1
Arthur Ulfeldt
  • 90,827
  • 27
  • 201
  • 284
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

Angel O'Sphere
  • 2,642
  • 20
  • 18