Golang动态调用方法

作者: adm 分类: go 发布时间: 2022-02-15 10:39

main.go

package main

import (
"lenu/call"
"reflect"
)


type FuncCollection map[string]reflect.Value

func main() {
_, _ = CallFunc("Hello", "执行Hello方法")
_, _ = CallFunc("World", "执行World方法")
}

func CallFunc(tableName string, args ... interface{}) (result []reflect.Value, err error) {
var router call.Routers
FuncMap := make(FuncCollection, 0)
rf := reflect.ValueOf(&router)
rft := rf.Type()
funcNum := rf.NumMethod()
for i := 0; i < funcNum; i ++ {
mName := rft.Method(i).Name
FuncMap[mName] = rf.Method(i)
}
parameter := make([]reflect.Value, len(args))
for k, arg := range args {
parameter[k] = reflect.ValueOf(arg)
}
result = FuncMap[tableName].Call(parameter)
return
}

package call:

router.go:

package call

type Routers struct {
}

hello.go

package call

import "log"

func (router *Routers) Hello(args ...interface{}) bool {
log.Println(args[0])
return true
}

world.go

package call

import "log"

func (router *Routers) World(args ...interface{}) bool {
log.Println(args[0])
return true
}

go run main.go会通过反射去调用Hello,World方法

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!