Home > OS >  invoke a method from a new instance (reflect.New) with reflection
invoke a method from a new instance (reflect.New) with reflection

Time:10-12

I want to instantiate an object in Go using reflection and call a method on it. However, I have no idea how to do this. I have tried something, but it does not work.

type foo struct {
    name string
}

func (f *foo) Bar() {
    f.name = "baz"
    fmt.Println("hi "   f.name)
}

func main() {
    t := reflect.TypeOf(&foo{})
    fooElement := reflect.New(t).Elem()
    fooElement.MethodByName("Bar").Call([]reflect.Value{})
}

CodePudding user response:

reflect.New works exactly like the new function, in that it returns an allocated pointer to the given type. This means you want pass the struct, not a pointer to the struct, to reflect.TypeOf.

t := reflect.TypeOf(foo{})
fooV := reflect.New(t)

Since you now have a pointer value of the correct type, you can call the method directly:

fooV.MethodByName("Bar").Call(nil)

https://play.golang.org/p/Aehrls4A8xB

  • Related