Summary of golang dynamic call method

Time:2022-6-3

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", "execute Hello method")
 _, _ = Callfunc ("world", "execute world method")
}
 
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 will call the Hello, world method through reflection

Summary of golang dynamic call method

This is the end of this article about the summary of golang dynamic invocation methods. For more information about golang dynamic invocation, please search the previous articles of developeppaper or continue to browse the relevant articles below. I hope you will support developeppaper in the future!