package main
import (
"fmt"
"reflect"
)
// 定义结构体
type MyStruct struct {
Value int
}
// 结构体方法1
func (m *MyStruct) Method1() {
fmt.Println("调用 Method1")
}
// 结构体方法2
func (m *MyStruct) Method2() int {
fmt.Println("调用 Method2")
return m.Value
}
func main() {
// 创建结构体实例
myObj := &MyStruct{Value: 10}
// 获取结构体实例的反射值
valueOf := reflect.ValueOf(myObj)
// 获取Method1方法
method1 := valueOf.MethodByName("Method1")
if method1.IsValid() {
method1.Call(nil)
} else {
fmt.Println("Method1 不存在")
}
// 获取Method2方法
method2 := valueOf.MethodByName("Method2")
if method2.IsValid() {
results := method2.Call(nil)
if len(results) > 0 {
result := results[0].Int()
fmt.Printf("Method2 返回值: %d\n", result)
}
} else {
fmt.Println("Method2 不存在")
}
}
- 定义结构体和方法:首先定义了一个
MyStruct
结构体,并为其定义了两个方法 Method1
和 Method2
。
- 获取反射值:通过
reflect.ValueOf
获取结构体实例的反射值。
- 获取并调用方法:使用
MethodByName
方法根据方法名获取对应的方法,然后通过 Call
方法调用该方法。对于有返回值的方法,获取其返回值并进行处理。