5

这是一个代码片段 -

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

reflect.ValueOf(client).MethodByName(endpoint).Call(inputs) 恐慌说 Call on a zero value。

4

1 回答 1

9

有几个问题:

  1. 如果svc1.Interface不是指针或接口,reflect.Value.Elem()则会恐慌(请参阅https://golang.org/pkg/reflect/#Value.Elem

  2. 如果endpoint参数字符串 的Invoke与目标方法的大小写不匹配,则会由于零值(invalid reflect.Value)而恐慌。请注意,您要调用的方法必须导出。

于 2017-06-15T14:06:07.577 回答