go通过名称来调用对应的方法

仅仅是为了学习go语言中的反射。

package main

import (
	"errors"
	"fmt"
	"reflect"
)

func Call(m map[string]interface{}, name string, params ...interface{}) ([]reflect.Value,error) {
	_, found := m[name]
	if !found {
		return nil, errors.New("map do not contains key ...")
	}
	fv := reflect.ValueOf(m[name])
	if fv.Kind() != reflect.Func {
		return nil, errors.New("the value of key is not a function")
	}

	if len(params) != fv.Type().NumIn() {
		return nil, errors.New("argument passed in does not match the function")
	}

	in := make([]reflect.Value, len(params))
	// for i := 0; i < len(params); i++ {
	// 	in[i] = reflect.ValueOf(params[i])
	// }
	for i, param := range params {
		in[i] = reflect.ValueOf(param)
	}
	return fv.Call(in), nil
}

func test1(name string) {
	fmt.Printf("hello,%s \n", name)
}

func test2(name string, age int) {
	fmt.Printf("hello,my name is %s ,%d years old", name, age)
}

func main() {
	m := make(map[string]interface{})
	m["test1"] = test1
	m["test2"] = test2

	result, err := Call(m, "test2", "hupeng", 12)
	if err != nil {
		panic(err)
	}
	fmt.Println(result)

}

posted @ 2014-11-28 14:58  纵酒挥刀斩人头  阅读(466)  评论(0编辑  收藏  举报