Golang动态调用方法小结
程序员文章站
2023-12-28 20:44:40
main.gopackage main import ( "lenu/call" "reflect") type funccollection map[string]reflect.value fu...
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动态调用内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!