我想使用Java构造函数作为一流的Clojure函数.我的用例是将一系列字符串转换为一系列Java对象,这些对象具有一个带有单个字符串的构造函数:
简单的Java对象:
public class Foo {
public Foo(String aString){
// initialize the Foo object from aString
}
}
Run Code Online (Sandbox Code Playgroud)
在Clojure中我想这样做:
(defn make-foo (memfn Foo. a-string))
(apply make-foo '("one" "two" "shoe"))
Run Code Online (Sandbox Code Playgroud)
apply应返回从Strings创建的Foo对象列表,但我得到了这个:
IllegalArgumentException No matching method found: org.apache.hadoop.io.Text. for class java.lang.String clojure.lang.Reflector.invokeMatchingMethod (Reflector.java:53)
Run Code Online (Sandbox Code Playgroud)
不要打扰.memfn
实际上已经弃用了匿名函数文字,您也可以使用它来调用构造函数,例如#(Foo. %)
.
此外,您的apply
调用将尝试make-foo
使用三个字符串args 调用一次.你可能想要:
(map #(Foo. %) ["one" "two" "three"])
Run Code Online (Sandbox Code Playgroud)