github.com/webx-top/com@v1.2.12/reflect.go (about) 1 package com 2 3 import ( 4 "fmt" 5 "reflect" 6 "strings" 7 ) 8 9 // TestReflect 测试反射:显示字段和方法信息 10 func TestReflect(v interface{}) { 11 val := reflect.ValueOf(v) 12 typ := val.Type() 13 if typ.Kind() == reflect.Ptr && typ.Elem().Kind() == reflect.Struct { 14 typ = typ.Elem() 15 val = val.Elem() 16 } 17 t := reflect.Indirect(val).Type() 18 name := t.Name() 19 fmt.Println("==================[" + name + ":]==================") 20 fmt.Println("PkgPath:", typ.PkgPath()) 21 fmt.Printf("Methods total: %v\n", typ.NumMethod()) 22 for i := 0; i < typ.NumMethod(); i++ { 23 vt := typ.Method(i) 24 vv := val.Method(i) 25 fmt.Printf("Type: %v => %v; Method name: %v\n", vv.Kind(), vv.Kind() == reflect.Func, vt.Name) 26 } 27 fmt.Println("-----------------------------------------------") 28 fmt.Printf("Fields total: %v\n", val.NumField()) 29 for i := 0; i < val.NumField(); i++ { 30 vt := typ.Field(i) 31 vv := val.Field(i) 32 var extInfo []string 33 if vt.Anonymous { 34 extInfo = append(extInfo, `anonymous`) 35 } 36 if vv.CanInterface() { 37 fmt.Printf("Type: %v => %v (%v); Index: %v; Field name: %v; Tag: %v\n", vv.Kind(), vv.Interface(), strings.Join(extInfo, `,`), i, vt.Name, 38 vt.Tag) 39 } else { 40 fmt.Printf("Type: %v => %v (%v); Index: %v; Field name: %v; Tag: %v\n", vv.Kind(), "<unexported>", strings.Join(extInfo, `,`), i, vt.Name, 41 vt.Tag) 42 } 43 } 44 fmt.Println("==================[/" + name + "]==================") 45 }