-
Notifications
You must be signed in to change notification settings - Fork 0
/
method_call_test.go
63 lines (52 loc) · 1.31 KB
/
method_call_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package main
import (
"fmt"
"reflect"
"testing"
)
type student struct {
Name string
Age int
}
func (stu *student) SetDefaults() {
stu.Name = "tangxin"
if stu.Age == 0 {
stu.Age = 100
}
}
// 没有传参的方法
func (stu *student) Greeting() {
fmt.Printf("hello %s, %d years old\n", stu.Name, stu.Age)
}
// 具有传参的方法
func (stu *student) Aloha(name string) {
fmt.Println("aloha,", name)
}
func Test_MethodCall(t *testing.T) {
stu := student{
Name: "wangwu",
}
// 注意
// 方法对象的方法接收者, 可以是 **指针对象** 也可以是 **结构体对象**
// 如果是指针对象的方法, **结构体对象** 是不能调用起方法的
rv := reflect.ValueOf(stu)
prv := reflect.ValueOf(&stu)
stu.Greeting()
methodCall(prv, "SetDefaults")
methodCall(rv, "Greeting") // 方法接收者不匹配,无法找到对应方法。
methodCall(prv, "Aloha", reflect.ValueOf("boss"))
}
// 对象方法调用
// rv 目标对象, method 方法名称, in 参数
func methodCall(rv reflect.Value, method string, in ...reflect.Value) {
// 通过方法名称获取 反射的方法对象
mv := rv.MethodByName(method)
// check mv 是否存在
if !mv.IsValid() {
fmt.Printf("mv is zero value, method %s not found\n", method)
return
}
// 调用
// nil 这里代表参数
mv.Call(in)
}