当前位置:主页 > 脚本语言 > Golang >

Golang动态调用方法小结

时间:2022-06-05 11:18:07 | 栏目:Golang | 点击:

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方法

您可能感兴趣的文章:

相关文章