【问题标题】:Reflection - method call panics with "call of reflect.Value.Elem on struct Value"反射 - 方法调用恐慌与“在结构值上调用 reflect.Value.Elem”
【发布时间】:2017-06-15 11:25:33
【问题描述】:

这是一个代码sn-p -

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.

【问题讨论】:

标签: go go-reflect


【解决方案1】:

有几个问题:

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

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

【讨论】:

  • 是的,在查看stackoverflow.com/questions/14116840/… 之后,我意识到试图找到一种方法将我的问题标记为该问题的重复,而不会对自己进行投票:D
  • 如果接口不是指针。将其更改为指针即可解决。
猜你喜欢
  • 1970-01-01
  • 2021-09-12
  • 2014-12-06
  • 1970-01-01
  • 2020-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-01
相关资源
最近更新 更多