go-反射

 

package main

import (
    "fmt"
    "reflect"
)

type Student struct {
    name string
    age  int
}

func (s Student) Set(name string, age int) {
    s.name = name
    s.age = age
}

func test(b interface{}) {

    val := reflect.ValueOf(b)
    kd := val.Kind()
    //判断是否为结构体

    switch kd {
    case reflect.Struct:
        {
            t := reflect.TypeOf(b)
            fmt.Println(t)

            //获取值
            value := reflect.ValueOf(b)

            //获取值类型
            ty := value.Interface()
            //转化为实际类型
            ss, ok := ty.(Student)
            if ok {
                fmt.Println(ss)
            }

            //通过反射获取方法个数
            Count := value.NumMethod()
            fmt.Printf("has %d Method\n", Count)
        }
    case reflect.Int:
        {
            t := reflect.TypeOf(b)
            fmt.Println(t)
        }
    }
}

func testInt(n interface{}) {
    val := reflect.ValueOf(n)
    //获取值
    c := val.Elem().Int()
    fmt.Println(c)

    //设置值
    val.Elem().SetInt(100)
    fmt.Println(val.Elem().Int())
}

func main() {
    //通过反射,获取变量信息
    s := Student{"break", 18}
    test(s)

    //通过反射,修改
    var nNum int = 10
    testInt(&nNum)
}

 

posted @ 2019-03-21 22:49  osbreak  阅读(134)  评论(0编辑  收藏  举报