我正在尝试在运行时从文件加载名称空间。对于这个命名空间,我希望有一个通用别名,这样我就可以使用独立于加载文件的实际命名空间的统一限定名称来访问该命名空间中的函数。
示例(不起作用):
;; bar_a.clj
(ns bar-a)
(defn hello-world [] "hello world a")
;; bar_b.clj
(ns bar-b)
(defn hello-world [] "hello world b")
;; foo.clj
(ns foo)
(defn init [ns-name]
(let [ns-symbol (symbol ns-name)]
(require `[ns-symbol :as bar])
(bar/hello-world))) ;; => No such var bar/hello world
;; during runtime when calling `init`!!!
我已经尝试过各种事情(load-file
, load
)并移动require
到不同的地方。到目前为止还没有运气。
我怎样才能做到这一点?
我认为问题在于符号的编译时解析不适用于动态加载的命名空间。在你的例子中bar/hello-world
已在编译时解决,但要求是在调用函数时动态完成的。我不知道有更好的解决方案,但你可以尝试这样的方法:
(ns foo)
(defn init [ns-name]
(require (symbol ns-name))
(let [bar (find-ns (symbol ns-name))]
((ns-resolve bar 'hello-world))))
当然,这不是很有效,因为每次调用该函数时都会解析名称空间和函数符号。但你应该能够明白这个想法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)