给定一个结构的任意实例,我希望能够执行所有不接受参数的公共方法.
例如,在下面的代码中,我希望能够执行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)
}
}
Run Code Online (Sandbox Code Playgroud)
reflect.TypeOf到reflect.ValueOfMethod,保证是接受零个参数Callfoo := reflect.ValueOf(X{})
for i := 0; i < foo.NumMethod(); i++ {
method := foo.Method(i)
if method.Type().NumIn() == 0 {
method.Call(nil)
}
}
Run Code Online (Sandbox Code Playgroud)
https://play.golang.org/p/KYAfaFlEjVt