dimanche 18 octobre 2015

How to extract the interface type name and package using reflection?

I need to know the type name and its path using reflection. type Type has a Name() and PkgPath() method but both of them return empty if the type is an interface.

However if I reflect a function and extract the type information of its arguments I get the correct type information. Should I assume it's a bug in the former case? Shouldn't TypeOf return the same type information regardless the context(e.g. type function parameter or type of a value) ?

package main

import (
    "fmt"
    "reflect"
    "http://ift.tt/1salFH3"
)

func main() {
    c := reflect.TypeOf(withValue(""))
    fn := func(context.Context){}
    fc := reflect.TypeOf(fn).In(0)
    fmt.Println(isContext(c),  isContext(fc), c, fc)
}

func isContext(r reflect.Type) bool {
    return r.PkgPath() == "http://ift.tt/1salFH3" && r.Name() == "Context"
}


func withValue(v interface{}) context.Context {
    return context.WithValue(context.TODO(), "mykey", v)
}

Prints

false true *context.valueCtx context.Context





Aucun commentaire:

Enregistrer un commentaire