golang利用反射调用类方法续

上一篇只是动态调用方法,这次我们得用反射动态获取方法和每个方法的参数.代码举例如下:

package main

import (
	"fmt"
	"reflect"
	"strconv"
)

type MyMath struct{
	a int
}


func (mm *MyMath) Add(num1 float64,num2 float64 ) float64 {
    reply := num1+num2 
	return reply
}


func (mm *MyMath) Sub(num1 float64,num2 float64 ) float64 {
    reply := num1-num2 
	return reply
}


func main() {
	m := new(MyMath)
	typ := reflect.TypeOf(m)
	//遍历方法
	for i := 0; i < typ.NumMethod(); i++ {
		method := typ.Method(i)
		mname := method.Name//方法名字
		fmt.Println("method:"+mname)
		fun := reflect.ValueOf(m).MethodByName(mname)
		ty := method.Type
		args := make([]reflect.Value, ty.NumIn()-1)
		//遍历参数
		for j:= 1; j< ty.NumIn(); j++ {
			//参数类型
			arg_type := ty.In(j).Kind().String()
			fmt.Println("参数" + strconv.Itoa(j) + ":" + arg_type)
			switch arg_type {
				case "float64":
					args[j-1] = reflect.ValueOf(float64(j))
				default:
					fmt.Println("i down'n knowon type " + arg_type)
				
			}
		}
		ret := fun.Call(args)
		fmt.Println(ret[0])
	}
	
}

这样,我们以后就可以知道一个类下有多少个方法,每个方法下有多少个参数且类型是什么,方便我们与其他弱语言相互调用的时候来处理类型!

此条目发表在 网站开发 分类目录,贴了 标签。将固定链接加入收藏夹。

评论功能已关闭。