自己实现的反射

package main

import (
    "errors"
    "fmt"
    "reflect"
)

type Student struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

type Teacher struct {
    name string
}

func (Student) Greet() {
    fmt.Println("hello")
}

func GetStructToJson(s interface{}) (map[interface{}]interface{}, error) {

    val := reflect.ValueOf(s)
    typ := reflect.TypeOf(s)
    kind := val.Kind()
    tm := make(map[interface{}]interface{})
    if kind != reflect.Struct {
        return tm, errors.New("不是struct")
    } else {
        for i := 0; i < typ.NumField(); i++ {
            key := typ.Field(i).Tag.Get("json")
            tm[key] = ConvertFieldValue(val.Field(i))
        }
    }
    for i := 0; i < val.NumMethod(); i++ {
        fmt.Println(typ.Method(i).Name)
        val.Method(i).Call(nil) //如果方法绑定的是指针对象这里不会执行读不到
    }
    return tm, nil

}

func ConvertFieldValue(value reflect.Value) interface{} {
    if value.Kind().String() == "string" {
        return value.String()
    }
    if value.Kind().String() == "int" {
        return value.Int()
    }
    return nil
}

func main() {
    m := Student{"夏华楼", 26}
    rm := reflect.ValueOf(&m).Elem() //反射修改结构体内容
    if rm.CanSet(){
        rm.Field(0).SetString("Jerry")
    }
    v, _ := GetStructToJson(m)
    fmt.Println(v)
    fmt.Println(Teacher{"allen"})
}




posted @ 2019-12-19 20:00  离地最远的星  阅读(94)  评论(0编辑  收藏  举报