go reflect 调用方法

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

 

posted on 2015-05-05 14:30  rojas  阅读(1207)  评论(0编辑  收藏  举报