3

To get a handle on a Java instance method which we can invoke later on, we can call the memfn function:

user=> (def g (memfn Integer/toString))
#'user/g

user=> (g 789)
"789"

This doesn't work for Java static methods:

user=> (def g (memfn Integer/toHexString))
#'user/g

user=> (g 789)
IllegalArgumentException No matching method found: toHexString for class java.lang.Long  clojure.lang.Reflector.invokeMatchingMethod (Reflector.java:52)

user=> (g)
ArityException Wrong number of args (0) passed to: user$g  clojure.lang.AFn.throwArity (AFn.java:437)

How can we get a handle to a Java static method, so we can invoke it later on?

1
  • 2
    The anonymous function literal, #(.foo ...), is generally preferred over memfn, so too would it be for static methods. Commented Dec 24, 2011 at 7:33

1 Answer 1

7

(defn g [x] (Integer/toHexString x))...? If you want, you can wrap that up in a macro, but there's not much left to do:

(defmacro static-fn [f] `(fn [x#] (~f x#)))
(def g (static-fn Integer/toHexString))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this gave me a nudge towards the much harder problem I had which required two levels of back-quoting and escaping.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.