Golang reflect反射使用(1)——读取结构体字段、执行其方法
package main import ( "fmt" "reflect" ) func main() { tonydon := &User{"TangXiaodong", 100, "0000123"} object := reflect.ValueOf(tonydon) myref := object.Elem() typeOfType := myref.Type() for i:=0; i<myref.NumField(); i++{ field := myref.Field(i) fmt.Printf("%d. %s %s = %v \n", i, typeOfType.Field(i).Name, field.Type(), field.Interface()) } tonydon.SayHello() v := object.MethodByName("SayHello") v.Call([]reflect.Value{}) } type User struct { Name string Age int Id string } func (u *User) SayHello() { fmt.Println("I'm " + u.Name + ", Id is " + u.Id + ". Nice to meet you! ") }
编译运行结果如下:
0. Name string = TangXiaodong
1. Age int = 100
2. Id string = 0000123
I'm TangXiaodong, Id is 0000123. Nice to meet you!
I'm TangXiaodong, Id is 0000123. Nice to meet you!
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。