给定结构的任意实例,我希望能够执行其所有不接受参数的公共(public)方法。
例如在下面的代码中,我希望能够在不知道 X{}.Foo() 和 X{}.Bar() 存在的情况下执行它们。
package main
import (
"fmt"
"reflect"
)
type X struct {
Y string
}
func (x X) Foo() string {
return x.Y
}
func (x X) Bar() {
}
func (x X) Baz(q string) {
}
func main() {
fooType := reflect.TypeOf(X{})
for i := 0; i < fooType.NumMethod(); i++ {
method := fooType.Method(i)
fmt.Println(method.Name)
}
}
最佳答案
- 更改
reflect.TypeOf
至reflect.ValueOf
- 检查 type的
Method
确保接受零参数 - 用
Call
调用方法
foo := reflect.ValueOf(X{})
for i := 0; i < foo.NumMethod(); i++ {
method := foo.Method(i)
if method.Type().NumIn() == 0 {
method.Call(nil)
}
}
关于go - 执行不接受参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51365591/