main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
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:
1
2
3
4
|
package call type Routers struct { } |
hello.go
1
2
3
4
5
6
7
8
|
package call import "log" func (router *Routers) Hello(args ...interface{}) bool { log.Println(args[0]) return true } |
world.go
1
2
3
4
5
6
7
8
|
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动态调用内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/AnPHPer/article/details/117703862