要获取struct所有方法,需用reflect.TypeOf获取类型对象,调用NumMethod()和Method(i)遍历;仅导出方法(首字母大写)且接收者为该类型值或指针方可访问。

要使用 Golang 反射获取 struct 的所有方法,关键在于:用 reflect.TypeOf 获取类型,再调用 Type.NumMethod() 和 Type.Method(i) 遍历;注意只有**导出方法(首字母大写)** 才能被反射访问,且接收者必须是该类型的值或指针。
获取 struct 类型的方法列表
反射操作需基于类型对象(reflect.Type),不是值对象(reflect.Value)。对 struct 实例调用 reflect.TypeOf(x) 得到其类型,再遍历方法:
- 用
t := reflect.TypeOf((*YourStruct)(nil)).Elem()获取 struct 类型(推荐,避免实例为 nil 导致 panic) - 或用
t := reflect.TypeOf(YourStruct{}),但确保 struct 字段可被合法初始化 - 循环
i := 0; i ,每次调用t.Method(i)返回reflect.Method结构体
Method 结构体字段说明
reflect.Method 包含以下常用字段:
-
Name:方法名(字符串,如
"GetName") - PkgPath:包路径,若为空字符串表示是导出方法;非空则为 unexported 方法(反射无法访问,不会出现在列表中)
-
Type:方法签名的类型(
reflect.Type),可用m.Type.In(i)、m.Type.Out(i)查看参数/返回值 -
Func:方法对应的函数值(
reflect.Value),可用于后续调用(需构造好接收者)
注意接收者类型与可调用性
反射能列出方法,但能否在运行时调用取决于接收者:
立即学习“go语言免费学习笔记(深入)”;
- 接收者为
T(值类型):传入reflect.ValueOf(structInstance)即可调用 - 接收者为
*T(指针类型):必须传入reflect.ValueOf(&structInstance) - 若接收者类型不匹配,
Func.Call()会 panic - 未导出方法(小写开头)不会出现在
NumMethod()结果中,反射不可见
简单示例代码
假设定义了如下 struct:
type User struct{ Name string }并有方法:
func (u User) GetName() string { return u.Name }func (u *User) SetName(n string) { u.Name = n }获取方法列表:
t := reflect.TypeOf(User{})for i := 0; i m := t.Method(i)
fmt.Printf("Name: %s, PkgPath: %q, Type: %s\n", m.Name, m.PkgPath, m.Type)
}
输出将包含 GetName;SetName 不会出现,因为其接收者是 *User,而 t 是 User 类型 —— 此时应改用 t := reflect.TypeOf(&User{}).Elem() 才能同时看到两个方法。
基本上就这些。不复杂但容易忽略接收者类型和导出规则。










