反射:按字符串构造

标签 reflection go

假设我有这个结构和一个方法:

package main

import (
    "fmt"
    "reflect"
)

type MyStruct struct {
}

func (a *MyStruct) AAction() {
    fmt.Println("Hello a")
}

现在,如果我想通过字符串调用方法“AAction”,我可以使用反射(这可行):

func main() {
    reflect.New(reflect.TypeOf(MyStruct{})).MethodByName("AAction").Call([]reflect.Value{})
}

问题是,我不想将 MyStruct{} 用作表达式,而是用作字符串。当然这是行不通的:

func main() {
    theStruct := "MyStruct"
    theAction := "AAction"
    reflect.New(reflect.TypeOf(theStruct)).MethodByName(theAction).Call([]reflect.Value{})
}

因为 reflect.Typeof(theStruct) 将是一个字符串。 我试着通读文档,遗憾的是,我找不到任何有用的东西。

我发现了这个类似的问题:Call a Struct and its Method by name in Go?
在已接受的问题下,OP 会问:

The issue in my case Is I cant not declare t is typed T, its must be some how I can declare t typed T by the name of T is string "T"

回答

[...] I would suggest to match the name against the string "T" somewhere in your code [...]

这并没有解决问题,因为我仍然需要在某处调用 MyStruct{}

问题是:有没有办法通过将名称作为字符串来使用结构? (无需手动将结构的名称映射到结构)

使用 reflect.TypeOf(MyStruct{}) 的工作版本: PlayGround
无效版本,显然是在字符串上调用方法:PlayGround

最佳答案

对不起,你不能。答案是:您可以。没有内置或预初始化的类型名称注册表。

要开始使用反射(reflect 包),您需要一个值(所讨论的类型)。基于string(类型的string名称),获取不到该类型的值,所以无法启动。

如果您只想通过 string 类型名称来执行您想要的操作,则需要在执行您想要的操作之前构建您自己的“注册表”。

关于反射:按字符串构造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36424907/

相关文章:

GoSublime 去定义

java - 通过反射获取字段名称是否是一项应该避免的昂贵操作?

c# - 使用反射调用实例方法抛出 TargetException。

go - 在没有安装 Go 的情况下安装 Go CLI 应用程序

go - 如何选择在运行时更新哪个结构成员?

go - 从 golang 应用程序发送字符串时出现意外的 StrComp 结果

templates - Golang http/模板变量

c# - 在运行时以编程方式获取摘要注释

c# - 将原始类型转换为可为空的对象

c# - 获取枚举的自定义属性的属性