pointers - 如何将一个 reflect.Type 转换为它的 ptr 类型?

标签 pointers go reflection types

我有一个 reflect.Type,我需要调用 MethodByName。如果方法定义在 T 类型上,找到它没有问题。如果在*T 上定义,此方法将返回无效值。所以我尝试将 T 转换为 *T 但失败了。这是我所做的:

首先,我尝试从该类型创建一个新值。创建后类型信息似乎丢失了。

t := reflect.TypeOf(src) // src is interface{} type
mt, exists := t.MethodByName(name)
if !exists {
    el := reflect.New(t)
    t = reflect.TypeOf(el)
    mt, exists = t.MethodByName(name)
    fmt.Println(t, mt, exists)
}

然后,我尝试直接从src(接口(interface)类型)获取类型,也失败了。

t := reflect.TypeOf(src)
mt, exists := t.MethodByName(name)
if !exists {
    t = reflect.TypeOf(&src) // *interface{} type, not what I want
    mt, exists = t.MethodByName(name)
    fmt.Println(t, mt, exists)
}

最佳答案

reflect.New()返回 reflect.Value() 类型的值.如果您将其传递给 reflect.TypeOf() ,那将是 reflect.Value 的描述符,而不是您的 *T

只需调用 Value.Type()来自 reflect.New() 返回的值:

el := reflect.New(t)
t = el.Type()
mt, exists = t.MethodByName(name)
fmt.Println(t, mt, exists)

关于pointers - 如何将一个 reflect.Type 转换为它的 ptr 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51378635/

相关文章:

c - 函数内部的 malloc 与 Main 中的 malloc

c - 用C打开文件时出现段错误

c - C类型语法如何避免循环定义?

c - 函数调用中的 Malloc 似乎在返回时被释放?

c# - 替代反射

java - Go 中 String 的 MD5 摘要与 Java 不同

go - 如何使用无服务器框架处理手动调用的 AWS lambda

http - 多次get参数请求只返回第一个参数

c# - 当 T 为 IEnumerable<TP> 时,将类型 T 的泛型参数转换为 List<TP>

java - 如何从 java.lang.Class 对象获取源文件名/行号