Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you cannot determine the class (possibly programmatically in a macro) during compile time, you need to resort to use reflection. This would do the same thing as eval does when it tries to compile the code. See <code>clojure.lang.Reflector/invokeStaticMethod</code>: <a href="https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/Reflector.java#L198" rel="nofollow">https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/Reflector.java#L198</a></p> <pre><code>(import 'clojure.lang.Reflector) ;; Here, you can pass *any string you have at runtime* (Reflector/invokeStaticMethod Integer "parseInt" (into-array ["1"])) </code></pre> <p>This can be used in arbitrary ways at runtime, since it's not a macro or a special form. For example, the name of the method could be given by the user via a GUI or though a socket at runtime.</p> <p>If you have the name of the class at compile time, you can use a macro as Nicolas suggested. However, it's unnecessary to construct the code to look like <code>(Integer/parseInt "1")</code>, since it's just syntactic sugar for the more basic (and macro friendly) <code>.</code> special form: <code>(. Integer parseInt "1")</code>.</p> <pre><code>;; Here, the method name needs to be a *string literal* (defmacro static-call "Takes a Class object, a string naming a static method of it and invokes the static method with the name on the class with args as the arguments." [class method &amp; args] `(. ~class ~(symbol method) ~@args)) </code></pre> <p>However, the only "real work" this macro performs is to convert the string into a symbol. You would probably just use the <code>.</code> special form in an outer macro (the one that acquires the names of the methods somehow, e.g. by getting those passed as arguments, or by reading them from a var or from a configuration file).</p> <pre><code>;; Use ordinary Clojure functions to construct this (def the-static-methods {:foo ["Integer" "parseInt"], :bar ["Long" "parseLong"]}) ;; Macros have access to all previously defined values (defmacro generate-defns [] (cons `do (for [[name-keyword [class-string method-string]] the-static-methods] `(defn ~(symbol (name name-keyword)) [x#] (. ~(symbol class-string) ~(symbol method-string) x#))))) (generate-defns) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload