-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreflect.go
43 lines (34 loc) · 860 Bytes
/
reflect.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
//反射中调用方法
package main
import (
"fmt"
"reflect"
"strconv"
)
type Mytype struct {
i int
Name string
}
func (m *Mytype) SetI(i int) {
m.i = i
}
func (m *Mytype) SetName(name string) {
m.Name = name
}
func (m *Mytype) Sprint() string {
return fmt.Sprintf("%p:", m) + "--name:" + m.Name + "--i:" + strconv.Itoa(m.i)
}
func main() {
mytype := &Mytype{26, "LIUHAI"}
fmt.Println(reflect.TypeOf(mytype))
mtV := reflect.ValueOf(&mytype).Elem()
fmt.Println(reflect.TypeOf(mtV))
fmt.Printf("%#v\n",mtV)
fmt.Println("Before:", mtV.MethodByName("Sprint").Call(nil)[0])
params := make([]reflect.Value, 1)
params[0] = reflect.ValueOf(18)
mtV.MethodByName("SetI").Call(params)
params[0] = reflect.ValueOf("reflection test")
mtV.MethodByName("SetName").Call(params)
fmt.Println("After:", mtV.MethodByName("Sprint").Call(nil)[0])
}