通過(guò)反射獲取結(jié)構(gòu)體對(duì)象屬性及其值
package main
import (
"fmt"
"reflect"
)
type A struct {
a interface{}
B bool
}
func main() {
a := A{}
fmt.Printf("a:%+v\n", a)
refType := reflect.TypeOf(a)
if refType.Kind() != reflect.Struct {
fmt.Println("Not a structure type.")
}
for i := 0; i < refType.NumField(); i++ {
fmt.Printf("file:%+v,\t", refType.Field(i).Name)
v := reflect.ValueOf(a)
val := v.FieldByName(refType.Field(i).Name)
fmt.Printf("value:%+v\n", val)
}
}
// output:
// a:{a:<nil> B:false}
// file:a, value:<nil>
// file:B, value:false