要获取struct所有方法,需用reflect.TypeOf获取类型对象,调用NumMethod()和Method(i)遍历;仅导出方法(首字母大写)且接收者为该类型值或指针方可访问。
要使用 Golang 反射获取 struct 的所有方法,关键在于:用 reflect.TypeOf 获取类型,再调用 Type.NumMethod() 和 Type.Method(i) 遍历;注意只有**导出方法(首字母大写)** 才能被反射访问,且接收者必须是该类型的值或指针。
反射操作需基于类型对象(reflect.Type),不是值对象(reflect.Value)。对 struct 实例调用 reflect.TypeOf(x) 得到其类型,再遍历方法:
t := reflect.Type
Of((*YourStruct)(nil)).Elem() 获取 struct 类型(推荐,避免实例为 nil 导致 panic)t := reflect.TypeOf(YourStruct{}),但确保 struct 字段可被合法初始化i := 0; i ,每次调用 t.Method(i) 返回 reflect.Method 结构体
reflect.Method 包含以下常用字段:
"GetName")reflect.Type),可用 m.Type.In(i)、m.Type.Out(i) 查看参数/返回值reflect.Value),可用于后续调用(需构造好接收者)反射能列出方法,但能否在运行时调用取决于接收者:
T(值类型):传入 reflect.ValueOf(structInstance) 即可调用*T(指针类型):必须传入 reflect.ValueOf(&structInstance)
Func.Call() 会 panicNumMethod() 结果中,反射不可见假设定义了如下 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{})输出将包含 GetName;SetName 不会出现,因为其接收者是 *User,而 t 是 User 类型 —— 此时应改用 t := reflect.TypeOf(&User{}).Elem() 才能同时看到两个方法。
基本上就这些。不复杂但容易忽略接收者类型和导出规则。