简体   繁体   English

如何将Clojure memfn与Java构造函数一起使用?

[英]How do I use Clojure memfn with a Java constructor?

I want to use a Java constructor as a first-class Clojure function. 我想使用Java构造函数作为一流的Clojure函数。 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对象,这些对象具有一个带有单个字符串的构造函数:

Simple Java object: 简单的Java对象:

public class Foo {
  public Foo(String aString){
    // initialize the Foo object from aString
  }
}

And in Clojure I want to do this: 在Clojure中,我想这样做:

(defn make-foo (memfn Foo. a-string))
(apply make-foo '("one" "two" "shoe"))

The apply should return a list of Foo objects created from Strings, but I'm getting this: 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)

Don't bother. 不要打扰。 memfn is practically deprecated in favor of the anonymous function literal, with which you can also invoke constructors, eg, #(Foo. %) . memfn实际上已被弃用,有利于匿名函数文字,您也可以使用它来调用构造函数,例如#(Foo. %)

Also, your apply call is going to try to invoke make-foo once with three string args. 此外,您的apply调用将尝试使用三个字符串args调用make-foo You probably instead want: 你可能想要:

(map #(Foo. %) ["one" "two" "three"])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM