英文:
invoke a method from a new instance (reflect.New) with reflection
问题
我想使用反射在Go中实例化一个对象并调用其方法。然而,我不知道如何做到这一点。我尝试了一些方法,但没有成功。
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{})
}
英文:
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{})
}
答案1
得分: 0
reflect.New
的工作方式与new
函数完全相同,它返回一个分配给指定类型的指针。这意味着你应该将结构体本身而不是指向结构体的指针传递给reflect.TypeOf
。
t := reflect.TypeOf(foo{})
fooV := reflect.New(t)
现在你有了正确类型的指针值,可以直接调用方法:
fooV.MethodByName("Bar").Call(nil)
链接:https://play.golang.org/p/Aehrls4A8xB
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论