详解Golang利用反射reflect动态调用方法

2020-01-28 13:38:18丽君

注册方法

我们再定义一个保存 M 所有方法的 map struct :


type Handler struct {
 Func  reflect.Value
 In   reflect.Type
 NumIn int
 Out  reflect.Type
 NumOut int
}

然后我们就可以来遍历结构体 M 的所有方法了:


func main() {
 handlers := make(map[string]*Handler)
 v := reflect.ValueOf(&M{})
 t := reflect.TypeOf(&M{})
 for i := 0; i < v.NumMethod(); i++ {
 name := t.Method(i).Name
 // 可以根据 i 来获取实例的方法,也可以用 v.MethodByName(name) 获取 
 m := v.Method(i)
 // 这个例子我们只获取第一个输入参数和第一个返回参数
 in := m.Type().In(0)
 out := m.Type().Out(0)
 handlers[name] = &Handler{
  Func:  m,
  In:   in,
  NumIn: m.Type().NumIn(),
  Out:  out,
  NumOut: m.Type().NumOut(),
 }
 }
}

Elem()

在学习 reflect 的过程中,我们发现 reflect.Value 和 reflect.Type 都提供了 Elem() 方法。

reflect.Value.Elem() 的作用已经在前面稍微提到了,主要就是返回一个 interface 或者 pointer 的值:

Elem returns the value that the interface v contains or that the pointer v points to. It panics if v's Kind is not Interface or Ptr. It returns the zero Value if v is nil.

reflect.Type.Elem() 的作用则是返回一个类型(如:Array,Map,Chan等)的元素的类型:

Elem returns a type's element type. It panics if the type's Kind is not Array, Chan, Map, Ptr, or Slice.

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易采站长站。