Golang reflect.MethodByName()函数及其示例

Golang reflect.MethodByName()函数及其示例

Go语言提供了内置支持运行时反射的实现,通过reflect包允许程序以任意类型操作对象。在Golang中,reflect.MethodByName()函数用于根据给定名称获取与v的方法对应的函数值。要访问此函数,需要在程序中导入reflect包。

语法:

func (v Value) MethodByName(name string) Value

参数: 该函数不接受任何参数。

返回值: 该函数返回与给定名称对应的v的方法的函数值。

下面的示例说明了在Golang中使用上述方法的方法:

示例1:

// Golang程序说明
// reflect.MethodByName()函数
     
package main
     
import (
    "fmt"
    "reflect"
)
   
// 主要功能
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程序说明
// reflect.MethodByName()函数
     
package main
     
import (
    "fmt"
    "reflect"
)
   
// 主要功能
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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程