gpt4 book ai didi

dynamic - elixir 动态模块调用

转载 作者:行者123 更新时间:2023-12-01 04:37:47 25 4
gpt4 key购买 nike

如何在名为 App.Reporting.Name 的模块中调用函数 func()

基于直到运行时才知道的字符串“名称”

使用 String.to_atom 或 to_existing_atom 不起作用:

 alias App.Reporting.Name
module = "name" |> String.capitalise |> String.to_atom
apply(module, :func, [])

没有别名,这也不起作用
module = "App.Reporting.Name" |> String.to_atom     
apply(module, :func, [])

我得到一个(UndefinedFunctionError)和(模块:“App.Reporting.Name”不可用)

谢谢

最佳答案

你的第二种方法几乎是正确的,你只需要前缀 Elixir.因为App.Reporting.Name等于 :"Elixir.App.Reporting.Name" ,而不是 :"App.Reporting.Name"因为 Elixir 为所有模块名称(以大写字母开头的名称)添加前缀 Elixir.在将其变成原子之前:

iex(1)> App.Reporting.Name == :"App.Reporting.Name"
false
iex(2)> App.Reporting.Name == :"Elixir.App.Reporting.Name"
true

所以,这段代码应该可以工作:
module = "Elixir.App.Reporting.Name" |> String.to_atom     
apply(module, :func, [])

应该这样:
module = Module.concat(App.Reporting, "name" |> String.capitalize |> String.to_atom)
apply(module, :func, [])

关于dynamic - elixir 动态模块调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41352591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com