码迷,mamicode.com
首页 > 其他好文 > 详细

go reflect 调用方法

时间:2015-05-05 15:47:43      阅读:113      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!