美文网首页
韩顺平 尚硅谷 反射题

韩顺平 尚硅谷 反射题

作者: FredricZhu | 来源:发表于2020-04-30 19:50 被阅读0次

适配器代码

package main

import (
    "fmt"
    "reflect"
    "testing"
)

type GMethod struct {
    Func interface{}
    Args []interface{}
}

func test1(a, b int) {
    fmt.Println(a, b)
}

func test2(a, b int, str string) {
    fmt.Println(a, b, str)
}

func sum(a, b int) int {
    return a + b
}

func Run(method GMethod) {
    _func := method.Func
    args := method.Args

    rFunc := reflect.ValueOf(_func)
    rArgs := make([]reflect.Value, 0)
    for _, arg := range args {
        rArgs = append(rArgs, reflect.ValueOf(arg))
    }

    rFunc.Call(rArgs)
}

func RunWithReturn(method GMethod) []interface{} {
    _func := method.Func
    args := method.Args

    rFunc := reflect.ValueOf(_func)
    rArgs := make([]reflect.Value, 0)
    for _, arg := range args {
        rArgs = append(rArgs, reflect.ValueOf(arg))
    }

    rRet := rFunc.Call(rArgs)
    actRet := make([]interface{}, 0)
    for _, ele := range rRet {
        actRet = append(actRet, ele.Interface())
    }

    return actRet
}

func TestMultiFunc(t *testing.T) {
    func1 := GMethod{
        Func: test1,
        Args: []interface{}{1, 2},
    }

    Run(func1)

    func2 := GMethod{
        Func: test2,
        Args: []interface{}{1, 2, "Hello"},
    }

    Run(func2)
}

func TestMultiFuncWithReturn(t *testing.T) {
    func3 := GMethod{
        Func: sum,
        Args: []interface{}{10, 20},
    }

    ret := RunWithReturn(func3)
    fmt.Println(ret[0])
}

遍历结构体代码

package main

import (
    "fmt"
    "reflect"
)

type Cal struct {
    Num1 int
    Num2 int
}

func (c *Cal) GetSub(name string) {
    res := c.Num1 - c.Num2
    fmt.Printf("%v完成了减法运算, %v-%v=%v\n", name, c.Num1, c.Num2, res)
}

func ReflectDemo(cal interface{}) {
    rValue := reflect.ValueOf(cal)
    rValueEle := rValue.Elem()
    num := rValueEle.NumField()

    for i := 0; i < num; i++ {
        fmt.Println(rValueEle.Field(i).Interface())
    }

    rMethod := rValue.Method(0)
    params := make([]reflect.Value, 0)
    params = append(params, reflect.ValueOf("Tom"))
    rMethod.Call(params)
}

func main() {
    c := Cal{
        Num1: 20,
        Num2: 9,
    }

    ReflectDemo(&c)
}

反射新建结构体代码

package main

import (
    "fmt"
    "reflect"
    "testing"
)

type User struct {
    UserId string
    Name   string
}

func ReflectStruct(st interface{}) interface{} {
    rType := reflect.TypeOf(st)

    rValue := reflect.New(rType)

    rValueEle := rValue.Elem()
    rValueEle.FieldByName("UserId").SetString("123456")
    rValueEle.FieldByName("Name").SetString("李四")

    return rValueEle.Interface()
}

func TestReflectStruct(t *testing.T) {
    var user User
    user = ReflectStruct(user).(User)
    fmt.Println(user)
}

相关文章

网友评论

      本文标题:韩顺平 尚硅谷 反射题

      本文链接:https://www.haomeiwen.com/subject/jtitghtx.html