Go反射调用方法

版权声明:本文为博主John Lau原创文章,未经博主允许不得转载 https://blog.csdn.net/GreatElite/article/details/78849921

Go提供了一个很重要的特性就是反射机制,反射机制对应处理一些特殊的应用场景非常实用。下文是Go反射调用函数的代码片段。

type Test struct {}

func (t *Test)PrintInfo(i int , s string) string{
    fmt.Println("call method PrintInfo i", i, ",s :", s)
    return s +strconv.Itoa(i)
}

func (t *Test)ShowMsg() string {
    fmt.Println("\nshow msg input 'call reflect'")
    return "ShowMsg"
}

func callReflect(any interface{}, name string, args... interface{}) []reflect.Value{
    inputs := make([]reflect.Value, len(args))
    for i, _ := range args {
        inputs[i] = reflect.ValueOf(args[i])
    }

    if v := reflect.ValueOf(any).MethodByName(name); v.String() == "<invalid Value>" {
        return nil
    }else {
        return v.Call(inputs)
    }

}

func callReflectMethod(){
    fmt.Printf("\n callReflectMethod PrintInfo :%s", callReflect(&Test{}, "PrintInfo", 10, "TestMethod")[0].String())
    fmt.Printf("\n callReflectMethod ShowMsg  %s", callReflect(&Test{}, "ShowMsg")[0].String())

    //<invalid Value> case
    callReflect(&Test{}, "ShowMs")
    if result := callReflect(&Test{}, "ShowMs"); result != nil {
        fmt.Printf("\n callReflectMethod ShowMs %s", result[0].String())
    }else {
        fmt.Println("\n callReflectMethod ShowMs didn't run ")
    }
    fmt.Println("\n reflect all ")
}

在main函数中调用函数callReflectMethod就可以运行上面代码片段了。

欢迎加入我的微信公众号

欢迎加入我的微信公众号

猜你喜欢

转载自blog.csdn.net/GreatElite/article/details/78849921