简体   繁体   中英

Calling a very simple clojure function from Java does not work

I'm very new in learning Clojure. This intended to be my first and very simple Clojure tries in which I call a simple Clojure method from inside java code. Unfortunately it does not work. The Compilation is successful and from the Clojure REPL the written function does as it was ordered, but when calling from Java it says the following:

Exception in thread "main" java.lang.IllegalArgumentException: Wrong number of args (2) passed to: ClojNum$-myinc
 at clojure.lang.AFn.throwArity(AFn.java:439)
 at clojure.lang.AFn.invoke(AFn.java:43)
 at com.experimental.clojure.test.ClojNum.myinc(Unknown Source)
 at com.experimental.clojure.java.JavaCaller.main(JavaCaller.java:14)

Here is the very simple Clojure code:

(ns com.experimental.clojure.test.ClojNum
  (:gen-class
   :init init
   :name com.experimental.clojure.test.ClojNum
   :methods [
             [myinc [int] int]
  ]))

(defn -init [] [[] (atom [])])    
(defn myinc "comment" [x] (+ x 1))    
(defn -myinc "comment" [x] (myinc x))

And the java part:

package com.experimental.clojure.java;

import com.experimental.clojure.test.ClojNum;

public class JavaCaller {
 /**
  * @param args
  */
 public static void main(String[] args) {
  int i = 0;
  System.out.println(i);
  ClojNum c = new ClojNum();
  i = c.myinc(0);  
  System.out.println(i);
 }
}

What did I do wrong? (Note again: This is primitve test code just to make a first successful function call)

Thanks for the help, I'm clueless.

Jeremy's link in the comments show you one way to call a static method in a clojure class. If you want to call a clojure function on an object instance, you need to add a parameter to your wrapper method definition:

(defn -myinc "comment" [this x] (myinc x))

The 'this' parameter is required for any non-static wrapper function. Clojure threw an exception because it received two parameters for a function only defined with one. Note, you do not change anything in your :gen-class :methods section or the myinc function definition itself.

The documentation is a bit sparse, but examples of this can be found at: http://clojure.org/compilation (the last example on the page shows instance methods).

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