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方法
栏 目:Golang
下一篇:golang通过node_exporter监控GPU及cpu频率、温度的代码
本文标题:Golang动态调用方法小结
本文地址:http://www.codeinn.net/misctech/203787.html