// Golang program to illustrate
// reflect.MethodByName() Function
package main
import (
"fmt"
"reflect"
)
// Main function
type T struct {}
func (t *T) GFG() {
fmt.Println("GeeksForGeeks")
}
func main() {
var t T
reflect.ValueOf(&t).MethodByName("GFG").Call([]reflect.Value{})
}
输出:
GeeksForGeeks
示例 2:
// Golang program to illustrate
// reflect.MethodByName() Function
package main
import (
"fmt"
"reflect"
)
// Main function
type YourT2 struct {}
func (y YourT2) MethodFoo(i int, oo string) {
fmt.Println(i)
fmt.Println(oo)
}
func Invoke(any interface{}, name string, args... interface{}) {
inputs := make([]reflect.Value, len(args))
for i, _ := range args {
inputs[i] = reflect.ValueOf(args[i])
}
reflect.ValueOf(any).MethodByName(name).Call(inputs)
}
func main() {
Invoke(YourT2{}, "MethodFoo", 10, "Geekforgeeks")
}
输出:
10
Geekforgeeks