简体   繁体   English

反思Clojure函数名称

[英]Reflect on Clojure Function Name

How do I use reflection in Clojure to extract the function name of a symbol that evaluates to a function? 如何在Clojure中使用反射来提取求值为函数的符号的函数名?

(require '[clojure.reflect :as r])
(defn foo [x] x)
(r/reflect foo)
=> {#clojure.reflect.Field ... 'gobbledygook}

Something about (map :name (:members (r/reflect foo))) ? 关于(map :name (:members (r/reflect foo)))吗?

No, please do not use str because it behaves differently. 不,请不要使用str因为它的行为有所不同。 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: 相反,请结合使用metavar调用:

(-> foo var meta)

This code returns a map of variable's metadata. 此代码返回变量元数据的映射。 The key :name holds the function name as a string: :name将函数:name保存为字符串:

(-> foo var meta :name)
foo

If you also want to have an ns's name, do the following: 如果您还想使用ns的名称,请执行以下操作:

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. 它获取名称空间对象,并使用ns-name函数作为字符串返回其名称。

Those methods do not depend on Clojure or REPL version and thus are more maintainable. 这些方法不依赖Clojure或REPL版本,因此更易于维护。

Looks like I can use str : 看起来我可以使用str

(str foo)
=> "#'my-project/foo"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM