This is a creation in
Article, where the information may have evolved or changed.
package testfuncimport("fmt")type Test struct{Name stringAge int}/*type Intio interface {Stringtest() string}*/func (this Test) Stringtest(){fmt.Println(this.Name)}func (this Test) Stringtest2(){fmt.Println("Stringtest2",this.Name)}func (this *Test) Stringtest1(i int){this.Age=ifmt.Println(this.Age)}func GetNumArgs(args []string,num int) string{if num==0 {num=1}return args[num]}
package mainimport("testfunc""reflect""fmt")func main(){d:=&testfunc.Test{"lyl",18}v:=reflect.ValueOf(d)ele:=v.Elem()t:=ele.Type()//读取这个对象的所有属性fmt.Println("读取这个对象的所有属性")for i:=0;i<t.NumField();i++{fmt.Println(t.Field(i).Name,ele.Field(i).Interface())}//读取对象方法fmt.Println("读取所有对象的方法")for i := 0; i < t.NumMethod(); i++ {fmt.Println(t.Method(i).Name)}fmt.Println("函数调用测试")ele.MethodByName("Stringtest").Call(nil)fmt.Println("带参函数调用")//func (this *Test) 需要指针调用fmt.Println("未修改的年龄",d.Age)iage:=reflect.ValueOf(11)v.MethodByName("Stringtest1").Call([]reflect.Value{iage})//参数转换成reflect.Valuefmt.Println("反射调用通过指针修改后的年龄",d.Age)}
Unable to traverse out pointer method