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

huangapple go评论75阅读模式
英文:

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

问题

例如,

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

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

英文:

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.

答案1

得分: 7

尝试这个:

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

playground示例

获取接口类型的反射类型是比较棘手的部分。请参考这个链接中的解释。

英文:

Try this:

t := reflect.TypeOf((*FooService)(nil)).Elem()
var s []string
for i := 0; i &lt; 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 https://stackoverflow.com/questions/7132848/how-to-get-the-reflect-type-of-an-interface for an explanation.

huangapple
  • 本文由 发表于 2017年7月13日 12:52:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/45071659.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定