Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list out the method name in an interface type?

Tags:

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.

like image 403
updogliu Avatar asked Jul 13 '17 04:07

updogliu


1 Answers

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.

like image 119
Bayta Darell Avatar answered Oct 11 '22 15:10

Bayta Darell