/
reflect.go
45 lines (43 loc) · 1.42 KB
/
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
44
45
package com
import (
"fmt"
"reflect"
"strings"
)
// TestReflect 测试反射:显示字段和方法信息
func TestReflect(v interface{}) {
val := reflect.ValueOf(v)
typ := val.Type()
if typ.Kind() == reflect.Ptr && typ.Elem().Kind() == reflect.Struct {
typ = typ.Elem()
val = val.Elem()
}
t := reflect.Indirect(val).Type()
name := t.Name()
fmt.Println("==================[" + name + ":]==================")
fmt.Println("PkgPath:", typ.PkgPath())
fmt.Printf("Methods total: %v\n", typ.NumMethod())
for i := 0; i < typ.NumMethod(); i++ {
vt := typ.Method(i)
vv := val.Method(i)
fmt.Printf("Type: %v => %v; Method name: %v\n", vv.Kind(), vv.Kind() == reflect.Func, vt.Name)
}
fmt.Println("-----------------------------------------------")
fmt.Printf("Fields total: %v\n", val.NumField())
for i := 0; i < val.NumField(); i++ {
vt := typ.Field(i)
vv := val.Field(i)
var extInfo []string
if vt.Anonymous {
extInfo = append(extInfo, `anonymous`)
}
if vv.CanInterface() {
fmt.Printf("Type: %v => %v (%v); Index: %v; Field name: %v; Tag: %v\n", vv.Kind(), vv.Interface(), strings.Join(extInfo, `,`), i, vt.Name,
vt.Tag)
} else {
fmt.Printf("Type: %v => %v (%v); Index: %v; Field name: %v; Tag: %v\n", vv.Kind(), "<unexported>", strings.Join(extInfo, `,`), i, vt.Name,
vt.Tag)
}
}
fmt.Println("==================[/" + name + "]==================")
}