Hello I have a main method in a Java class and I would like to access and run my clojure functions from my java classe开发者_如何学JAVAs, is that possible right?
Help please
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
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.
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.
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
精彩评论