如何列出接口类型中的方法名称? [英] How to list out the method name in an interface type?

查看:43
本文介绍了如何列出接口类型中的方法名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,

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

我正在尝试使用运行时反射获取列表 ["Foo1","Foo2"] .

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

推荐答案

尝试一下:

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

游乐场示例

获取接口类型的reflect.Type是棘手的部分.请参阅如何获取反射.接口的类型?进行解释.

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.

这篇关于如何列出接口类型中的方法名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆