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動態調用內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!