我可以在Clojure中部分Java方法调用吗?

时间:2013-12-11 13:33:45

标签: clojure clojure-java-interop

我有一个对象的方法。

myObject.myMethod(1)

我可以在Clojure中调用它

(.myMethod myObject 1)

我也可以使用词汇环境中的信息来调用它

(let [x 1] (.myMethod myObject x))

我可以部分地这样做吗? E.g。

(let [myPartial (partial .myMethod myObject)]
      (myPartial 1))

这给了我一个

  

java.lang.RuntimeException:无法在此上下文中解析符号:.myMethod

我目前正在使用匿名函数

进行此工作
(let [myThing #(.myMethod myObject %)]
      (myThing 1))

但是如果在这种情况下使用部分会很好。有可能吗?

我确信答案将与绑定和发送有关,但我还不知道在编译和执行过程中发生了什么。

1 个答案:

答案 0 :(得分:11)

您可以部分使用(memfn)。

(memfn myMethod args)

在REPL中:

user=> (doc memfn)
-------------------------
clojure.core/memfn
([name & args])
Macro
Expands into code that creates a fn that expects to be passed an
object and any args and calls the named instance method on the
object passing the args. Use when you want to treat a Java method as
a first-class fn. name may be type-hinted with the method receiver's
type in order to avoid reflective calls.