如何在接口类型中列出方法名称?

upd*_*liu 5 reflection go

例如,

type FooService interface {
    Foo1(x int) int
    Foo2(x string) string
}
Run Code Online (Sandbox Code Playgroud)

我试图做的是["Foo1", "Foo2"]使用运行时反射获取列表。

Cer*_*món 7

尝试这个:

t := reflect.TypeOf((*FooService)(nil)).Elem()
var s []string
for i := 0; i < t.NumMethod(); i++ {
    s = append(s, t.Method(i).Name)
}
Run Code Online (Sandbox Code Playgroud)

游乐场示例

获取接口类型的reflect.Type 是棘手的部分。请参阅如何获取接口的reflect.Type?以获得解释。