Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Clojure中调用非静态Java方法_Java_Clojure_Interop - Fatal编程技术网

在Clojure中调用非静态Java方法

在Clojure中调用非静态Java方法,java,clojure,interop,Java,Clojure,Interop,在Clojure中调用静态Java方法是平滑的;没问题。但当我调用一个非静态方法时,它会抛出一个错误,尽管我尝试了点(.)表示法的几种变体,如中所述 Java类: public class CljHelper { public void test(String text) { System.out.println(text); } } Clojure代码: (ns com.acme.clojure.Play (:import [com.acme.helpers CljH

在Clojure中调用静态Java方法是平滑的;没问题。但当我调用一个非静态方法时,它会抛出一个错误,尽管我尝试了点(.)表示法的几种变体,如中所述

Java类:

public class CljHelper {

  public void test(String text) {
    System.out.println(text);
  }

}
Clojure代码:

(ns com.acme.clojure.Play
  (:import [com.acme.helpers CljHelper]))

(. CljHelper test "This is a test")  
错误:

java.lang.IllegalArgumentException: No matching method: test
java.lang.NullPointerException: null
这是另一次尝试,它使Java方法得以执行,但紧接着抛出一个错误:

(defn add-Id
  [x]
  (let [c (CljHelper.)]
    ((.test c x))))        ;;; java.lang.NullPointerException: null in this line

(add-Id "id42")
错误:

java.lang.IllegalArgumentException: No matching method: test
java.lang.NullPointerException: null

这是最简单的方法。生成java类计算:

package demo;

public class Calc {
  public int answer() {
    return 42;
  } 
}
从Clojure开始称之为:

(ns tst.demo.core
  (:use tupelo.core tupelo.test)
  (:import [demo Calc]))

(let [c (Calc.)]                   ; construct an instance of Calc
  (println :answer (.answer c)))   ; call the instance method
结果:

:answer 42

您可以开始。这里有两个不同的问题。在第一个示例中,您试图调用类
CljHelper
上的方法。您应该在实例上调用它,而不是在类上调用它

(.test(CljHelper.“这是一个测试”)
对于第二个示例,您有一组额外的括号。因此,您正确地调用了方法
test
,但随后您获取了结果,该结果为null,并尝试将其作为函数调用。所以只要去掉括号就行了

(定义添加id
[x]
(让[c(CljHelper.)]
(.测试c x)))

谢谢,艾伦。我已经实施了你的解决方案。Java方法已执行,但它会立即抛出Java.lang.NullPointerException:null。将当前代码添加到问题中。您可能忘了在
c
之后添加
文本,我已经删除了额外的一组括号,如上面的回答中所述,现在它可以工作了。删除外部参数
(.test c x))
-您正在调用测试结果,也就是说,无括号总是有意义的,不能像大括号那样加上括号使事情更清楚;还有一组额外的参数。是的,两个问题的建议解决方案都有效。谢谢