首页 > 其他 > 详细

go reflect 调用方法

时间:2015-05-05 15:45:45      阅读:283      评论:0      收藏:0      [点我收藏+]
package main

import (
    "fmt"
    "reflect"
)

type A struct {
}

func (A) Test() {
    fmt.Println("gooooo reflect call empty param method")
}

func (A) TestwithParam(ap string, bp string) {
    fmt.Println("gooooo reflect call with Param method:", ap, bp)
}

func main() {

    var a A
    f := reflect.ValueOf(a)
    //空参数时方法调用 一 序号
    f.Method(0).Call(nil) //gooooo method

    //空参数时方法调用 二 方法名
    in := make([]reflect.Value, 0)
    f.MethodByName("Test").Call(in) //gooooo method

    //多参数调用
    parray := []string{"hello", "reflect"}
    inp := make([]reflect.Value, len(parray))

    for k, param := range parray {
        inp[k] = reflect.ValueOf(param)
    }

    f.MethodByName("TestwithParam").Call(inp)
}

//打印
//gooooo reflect call empty param method
//gooooo reflect call empty param method
//gooooo reflect call with Param method: hello reflect

 

go reflect 调用方法

原文:http://www.cnblogs.com/rojas/p/4479063.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!