golang 反射应用(二)

golang反射应用(二)

package test

import (
    "reflect"
    "testing"
)

//定义适配器
func TestReflect(t *testing.T){
    //声明回调函数
    call1 := func(v1,v2 int){
        t.Log(v1,v2)   //1 2
    }

    call2 := func(v1,v2 int,s string){
        t.Log(v1,v2,s)   //1 2 test2
    }

    //定义全局变量
    var (
        function reflect.Value
        inValue []reflect.Value
        n int
    )

    bridge := func(call interface{},args... interface{}){
        n = len(args)
        inValue = make([]reflect.Value,n)
        for i:=0;i<n;i++{
            inValue[i] = reflect.ValueOf(args[i])
        }

        //将一个interface转换我Value类型
        function = reflect.ValueOf(call)
        //传入参数,直接去调用函数
        function.Call(inValue)
    }

    //桥接函数,调用不同的函数
    bridge(call1,1,2)
    bridge(call2,1,2,"test2")
}

type user struct {
    UserId string
    Name string
}

//实例化一个对象,并为该实例赋值
func TestRelectStructPtr(t *testing.T){
    var (
        model *user
        st reflect.Type
        elem reflect.Value
    )

    st = reflect.TypeOf(model)   //获取类型 *user
    t.Log("reflect.TypeOf",st.Kind().String())   //ptr
    st = st.Elem()   //st指向的类型
    t.Log("reflect.TypeOf.Elem",st.Kind().String())  //struct
    elem = reflect.New(st)   //New返回一个Value类型值,该值持有一个指向类型为type的新申请的零值指针
    t.Log("reflect.New",elem.Kind().String())  //ptr
    t.Log("reflect.New.Elem",elem.Elem().Kind().String())   //reflect.New.Elem struct

    //model就是创建的user结构体变量(实例)
    model = elem.Interface().(*user)  //model是*user 它的指向和elem是一样的
    elem =elem.Elem()  //取得elem指向的值

    elem.FieldByName("UserId").SetString("123456")  //赋值
    elem.FieldByName("Name").SetString("jack")
    t.Log("model model.Name",model,model.Name)    //model model.Name &{123456 jack} jack
}

总结:
(1.)反射的应用有适配器定义,结构体创建和对结构体字段进行操作

猜你喜欢

转载自www.cnblogs.com/tomtellyou/p/10467260.html
今日推荐