lundi 16 juillet 2018

Execute methods which don't accept arguments

Given an arbitrary instance of a struct, I'd like to be able to execute all of its public methods which don't accept arguments.

For example in the code below, I'd like to be able to execute X{}.Foo() and X{}.Bar() without knowing that they exist.

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)
    }
}





Aucun commentaire:

Enregistrer un commentaire