简体   繁体   English

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

[英]How to convert one reflect.Type to its ptr type?

I have one reflect.Type and I need to call MethodByName . 我有一个reflect.Type,我需要调用MethodByName If the method is defined on type T , no problem to find it. 如果方法是在类型T上定义的,那么找到它就没问题了。 If it's defined on *T , this mehtod will return invalid value. 如果它在*T上定义,则此方法将返回无效值。 So I tried to convert T to *T and failed. 所以我试图将T转换为*T并失败。 Here is what I do: 这是我做的:

First, I tried to create a new value from the type. 首先,我尝试从该类型创建一个新值。 Type infomation seems to lost after creation. 类型信息似乎在创建后丢失了。

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)
}

Then, I tried to get type directly from src(the interface type), and failed also. 然后,我试图直接从src(接口类型)获取类型,也失败了。

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() returns a value of type reflect.Value() . reflect.New()返回一个reflect.Value()类型的值。 If you pass this to reflect.TypeOf() , that will be the descriptor of reflect.Value , not your *T . 如果你将它传递给reflect.TypeOf() ,那将是reflect.Value的描述符,而不是你的*T

Simply call Value.Type() from the value returned by reflect.New() : 只需从Value.Type()返回的值调用Value.Type() reflect.New()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM