How do I use reflection in Clojure to extract the function name of a symbol that evaluates to a function?
(require '[clojure.reflect :as r])
(defn foo [x] x)
(r/reflect foo)
=> {#clojure.reflect.Field ... 'gobbledygook}
Something about (map :name (:members (r/reflect foo)))
?
No, please do not use str
because it behaves differently. In my example, here is what I've got:
user=> (defn foo [x] x)
#'user/foo
user=> (str foo)
"user$foo@7cb20059"
Instead, use combination of meta
and var
calls:
(-> foo var meta)
This code returns a map of variable's metadata. The key :name
holds the function name as a string:
(-> foo var meta :name)
foo
If you also want to have an ns's name, do the following:
user=> (-> foo var meta :ns ns-name)
user
It gets the namespace object and returns its name with the ns-name
function as a string.
Those methods do not depend on Clojure or REPL version and thus are more maintainable.
Looks like I can use str
:
(str foo)
=> "#'my-project/foo"
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.