反射 - 方法调用与"call of reflect.Value.Elem on struct Value"恐慌



这是一个代码片段 -

type Gateway struct {
    Svc1 svc1.Interface
    Svc2 svc2.Interface
}
func (g *Gateway) GetClient(service string) interface{} {
    ps := reflect.ValueOf(g)
    s := ps.Elem()
    f := s.FieldByName(strings.Title(service))
    return f.Interface()
}
func (g *Gateway) Invoke(service string, endpoint string, args... 
    interface{}) []reflect.Value {
    log.Info("Gateway.Invoke " + service + "." + endpoint)
    inputs := make([]reflect.Value, len(args))
    for i, _ := range args {
        inputs[i] = reflect.ValueOf(args[i])
    }
    client := g.GetClient(service)
    return reflect.ValueOf(client).Elem().MethodByName(endpoint).Call(inputs)
}

GetClient("svc1"( 工作正常。

但是,当我调用Invoke("svc1","endpoint1",someArg(时,它会惊慌失措地说 -

reflect: call of reflect.Value.Elem on struct Value

反映。ValueOf(客户端(。MethodByName(endpoint(。呼叫(输入(紧急显示调用零值。

有几个问题:

  1. 如果svc1.Interface不是指针或接口,reflect.Value.Elem()会死机(见 https://golang.org/pkg/reflect/#Value.Elem(

  2. 如果 Invokeendpoint参数字符串与目标方法的大小写不匹配,它将由于零值 (invalid reflect.Value ( 而死机。请注意,必须导出要调用的方法。

最新更新