GOLANG学习29. 反射获取字段、方法、调用
package main
import (
"encoding/json"
"fmt"
"reflect"
)
//结构体
type Student struct {
Name string
Age int
Score float32
}
//定义结构体方法
func (s Student) Sleep(name string, age int, score float32) {
s.Name = name
s.Age = age
s.Score = score
fmt.Printf("%s is sleep\n", s.Name)
}
func (s Student) Study() {
fmt.Println("is study")
}
//反射
func do(i interface{}) {
val := reflect.ValueOf(i)
kd := val.Kind()
//判断是不是struct类型
if kd != reflect.Struct {
fmt.Println("this is not struct")
}
//获取结构体参数字段数量和值和类型
numOfFeild := val.NumField()
fmt.Println("stuct num field:", numOfFeild)
for i := 0; i < numOfFeild; i++ {
fmt.Printf("the %d feild is value %v, is type %v\n", i, val.Field(i), val.Field(i).Kind())
}
//获取结构体方法数量
numOfMethod := val.NumMethod()
fmt.Println("stuct method field:", numOfMethod)
//调用结构体里面的方法
//var params []reflect.Value
val.Method(1).Call(nil)
}
func main() {
var stu Student = Student{
Name: "张正山",
Age: 30,
Score: 98.9,
}
do(stu)
//json打包json result is {"Name":"张正山","Age":30,"Score":98.9}
result, _ := json.Marshal(stu)
fmt.Println("json result is ", string(result))
}