How to list out the method name in an interface ty

2020-06-23 09:49发布

For example,

type FooService interface {
    Foo1(x int) int
    Foo2(x string) string
}

What I am attempting to do is getting list ["Foo1", "Foo2"] using runtime reflection.

标签: go reflection
1条回答
唯我独甜
2楼-- · 2020-06-23 09:52

Try this:

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

playground example

Getting the reflect.Type for the interface type is the tricky part. See How to get the reflect.Type of an interface? for an explanation.

查看更多
登录 后发表回答