简体   繁体   中英

How do I use Clojure memfn with a Java constructor?

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:

Simple Java object:

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

And in Clojure I want to do this:

(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:

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. %) .

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"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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