如何通过反射从名称获取类型表示形式? [英] How to get Type representation from name via reflection?

查看:68
本文介绍了如何通过反射从名称获取类型表示形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在Go中使用反射库来查找类型名称为其类型表示?

Is there a way to use the reflection libraries in Go to go from the name of a type to its Type representation?

我有一个库,用户需要在其中提供某些代码生成的Type表示形式.我知道这一定是有可能的,因为它们只能创建该类型的变量并调用TypeOf函数,但是有没有一种方法可以避免这种情况,而只是从名称中获取表示形式?

I've got a library where the user needs to provide Type representations for some code generation. I know it must be possible (in a sense) because they can just create a variable of that type and call the TypeOf function, but is there a way to circumvent this and just get representation from the name?

推荐答案

这个问题不是很明确,可以用两种方式解释,一种是不可能",另一种是不可能".另一个答案是肯定的.

The question is not quite explicit, it can be interpreted in 2 ways, to one of which the answer is no, not possible; and the other to which the answer is yes, it's possible.

如果类型名称是作为 string 值提供的,则在运行时是不可能的,因为未明确引用的类型可能无法编译为最终的可执行二进制文件(因此显然变得不可访问),在运行时为未知").有关详细信息,请参见拆分客户端/服务器代码.有关可能的解决方法,请参见使用Golang中的特殊前缀或后缀.

If the type name is provided as a string value, then at runtime it's not possible as types that are not referred to explicitly may not get compiled into the final executable binary (and thus obviously become unreachable, "unknown" at runtime). For details see Splitting client/server code. For possible workarounds see Call all functions with special prefix or suffix in Golang.

如果我们正在谈论编码"时间(编写/生成源代码),那么可能无需创建/分配给定类型的变量并调用

If we're talking about "coding" time (source code writing / generating), then it's possible without creating / allocating a variable of the given type and calling reflect.TypeOf() and passing the variable.

您可以从 pointer 到类型,然后使用 typed的 nil 指针值而不进行分配,并且可以从其指针进行导航 reflect.Type 描述符到基准的描述符类型(或 element 类型)使用 Type.Elem()的指针.

You may start from the pointer to the type, and use a typed nil pointer value without allocation, and you can navigate from its reflect.Type descriptor to the descriptor of the base type (or element type) of the pointer using Type.Elem().

它是这样的:

t := reflect.TypeOf((*YourType)(nil)).Elem()

上面的类型描述符 t 与下面的 t2 相同:

The type descriptor t above will be identical to t2 below:

var x YourType
t2 := reflect.TypeOf(x)

fmt.Println(t, t2)
fmt.Println(t == t2)

上述应用程序的输出(在转到游乐场上尝试):

Output of the above application (try it on the Go Playground):

main.YourType main.YourType
true

这篇关于如何通过反射从名称获取类型表示形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆