Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a very simple clojure function from Java does not work

Tags:

java

clojure

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.

like image 400
Ujvari Avatar asked Jan 24 '11 14:01

Ujvari


1 Answers

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).

like image 183
robert_x44 Avatar answered Nov 09 '22 04:11

robert_x44