这是一个代码片段 -
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)
}
Run Code Online (Sandbox Code Playgroud)
GetClient("svc1") 工作正常。
但是,当我调用 Invoke("svc1", "endpoint1", someArg) 时,它会恐慌地说 -
reflect: call of reflect.Value.Elem on struct Value
Run Code Online (Sandbox Code Playgroud)
reflect.ValueOf(client).MethodByName(endpoint).Call(inputs) 恐慌说调用零值。
小智 7
有几个问题:
如果svc1.Interface
不是指针或接口,reflect.Value.Elem()
将恐慌(参见https://golang.org/pkg/reflect/#Value.Elem)
如果 的endpoint
参数字符串Invoke
与目标方法的大小写不匹配,则会由于零值 ( invalid reflect.Value
)而造成恐慌。请注意,您要调用的方法必须是导出的。