Search code examples
javamethodsclojurequoteclojure-java-interop

Unquote a java method in clojure


How do I parameterize calls methods in Clojure?

Example:

(def url (java.net.URL. "http://www.google.com"))
(.getHost url) ;; works!
(def host '.getHost)
(host url) ;; Nope :(
(~host url) ;; Nope :(
(eval `(~host url)) ;; Works :s

Solution

  • Right solution:

    (def url (URL. "http://www.google.com"))
    (def host 'getHost)
    (defn dynamic-invoke
      [obj method arglist]
      (.invoke (.getDeclaredMethod
                 (class obj) (name method) nil)
               obj (into-array arglist)))
    (dynamic-invoke url host [])