简体   繁体   中英

access clojure via java classes

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

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.

检查Java脚本API,以调用脚本文件中的函数: http : //download.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM