使用反射(reflection)从一个新实例(reflect.New)中调用一个方法。

huangapple go评论74阅读模式
英文:

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)

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

huangapple
  • 本文由 发表于 2021年10月12日 04:58:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/69532430.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定