Go 语言提供了运行时反射的内置支持实现,并允许程序在反射包的帮助下操作任意类型的对象。 Golang 中的reflect.NumMethod()函数用于获取值的方法集中导出方法的数量。要访问此函数,需要在程序中导入反射包。
Syntax:
Parameters: This function does not accept any parameter.
Return Value: This function returns the number of exported methods in the value’s method set.
下面的例子说明了上述方法在 Golang 中的使用:
示例 1:
func (v Value) NumMethod() int
输出:
// Golang program to illustrate
// reflect.NumMethod() Function
package main
import (
"fmt"
"reflect"
)
type gfg struct {
Prop string
}
func (f gfg) Geek1() string {
return f.Prop
}
func (f gfg) Geek2() {
}
// Main function
func main() {
fooType := reflect.TypeOf(gfg{})
for i := 0; i < fooType.NumMethod(); i++ {
method := fooType.Method(i)
fmt.Println(method.Name)
}
}
示例 2:
Geek1
Geek2
输出:
// Golang program to illustrate
// reflect.NumMethod() Function
package main
import (
"log"
"reflect"
)
type Reindeer string
func (r Reindeer) TakeOff() {
log.Printf("%q lifts off.", r)
}
func (r Reindeer) Land() {
log.Printf("%q gently lands.", r)
}
func (r Reindeer) ToggleNose() {
if r != "rudolph" {
panic("invalid reindeer operation")
}
log.Printf("%q nose changes state.", r)
}
func main() {
r := Reindeer("rudolph")
t := reflect.TypeOf(r)
for i := 0; i < t.NumMethod(); i++ {
m := t.Method(i)
log.Printf("%s", m.Name)
}
}