I was trying to generalize my code by using reflection to call all methods of a type. It's easy and straightforward but there is a problem with that, reflection.TypeOf(T).NumMethods (or other methods) ignores methods which used receiver type as a pointer. For example this small code will print 1 instead of 2:
package main
import (
"fmt"
"reflect"
)
type Foo struct {}
func (f Foo) Bar() {}
func (f *Foo) Baz() {}
func main() {
obj := Foo{}
fmt.Println(reflect.TypeOf(obj).NumMethod())
}
You can run in playground. It prints 1 because of Bar method. If you delete the pointer (*) from Baz, it will print 2.
My question is how can I list all methods regardless of receiver type.
Thanks
You can just use the pointer of obj
to get all Methods:
func main() {
obj := &Foo{}
fmt.Println(reflect.TypeOf(obj).NumMethod())
}
Get pointer to method with pointer type receiver. In case you wants to call the method by name using reflection here is the code.
package main
import (
"fmt"
"reflect"
)
type Foo struct{}
func (f Foo) Bar() {
fmt.Println("Inside Bar")
}
func (f *Foo) Baz() {
fmt.Println("Inside Baz")
}
func main() {
rfl := reflect.ValueOf(&Foo{})
v := rfl.MethodByName("Baz")
results := v.Call(nil)
fmt.Printf("%#v
", results)
fmt.Println(reflect.TypeOf(&Foo{}).NumMethod())
}