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 (updated clojure 1.12):

    (def url (java.net.URL. "http://www.google.com"))
    (def host java.net.URL/.getHost)
    (host url)
    => "www.google.com"
    
    ;; old//fully dynamic version
    (def host-sym 'getHost)
    (defn dynamic-invoke
      [obj method & arglist]
      (.invoke (.getDeclaredMethod
                 (class obj) (name method) nil)
               obj (into-array arglist)))
    (dynamic-invoke url host-sym)