问题描述
我想使用Java构造函数作为第一类Clojure函数。我的用例是将一个字符串序列转换为一个Java对象序列,其中有一个带有单个字符串的构造函数:
I want to use a Java constructor as a first-class Clojure function. My use-case is to transform a sequence of strings into a sequence of Java objects that have a constructor with a single string:
简单的Java对象:
public class Foo {
public Foo(String aString){
// initialize the Foo object from aString
}
}
在Clojure中,我想这样做:
And in Clojure I want to do this:
(defn make-foo (memfn Foo. a-string))
(apply make-foo '("one" "two" "shoe"))
apply应该返回从Strings创建的Foo对象的列表,得到这个:
The apply should return a list of Foo objects created from Strings, but I'm getting this:
IllegalArgumentException No matching method found: org.apache.hadoop.io.Text. for class java.lang.String clojure.lang.Reflector.invokeMatchingMethod (Reflector.java:53)
推荐答案
不要打扰。 memfn
实际上已被弃用,有利于匿名函数文字,你也可以使用它调用构造函数,例如#(Foo。%)
。
Don't bother. memfn
is practically deprecated in favor of the anonymous function literal, with which you can also invoke constructors, e.g., #(Foo. %)
.
此外,您的 apply
调用将尝试调用 make-foo
一次,有三个字符串参数。您可能想要:
Also, your apply
call is going to try to invoke make-foo
once with three string args. You probably instead want:
(map #(Foo. %) ["one" "two" "three"])
这篇关于如何使用Java构造函数使用Clojure memfn?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!