【问题标题】:How to dynamically call all methods of a struct in Golang? [duplicate]如何在 Golang 中动态调用结构的所有方法? [复制]
【发布时间】:2019-09-10 00:27:04
【问题描述】:

我正在构建一个库,一旦将方法添加到结构中,我们希望使用某种方法列表自动调用它们而无需使用。

我想通过调用此处链接到How to dump methods of structs in Golang? 的所有转储方法来构建这里的工作。

package main

import (
    "fmt"
    "reflect"
)

type Foo struct {
    Prop string
}

func (f Foo) Bar(i int) {
    fmt.Println("Called from Foo.Bar()")
}

func (f Foo) Baz(i int) {
    fmt.Println("Called from Foo.Baz()")
}

func (f Foo) Floop(i int) {
    fmt.Println("Called from Foo.Floop()")
}

func main() {
    fooType := reflect.TypeOf(&Foo{})

    fmt.Println("--- Calling methods ---")
    for i := 0; i < fooType.NumMethod(); i++ {
        method := fooType.Method(i)

        method.Func.Call(nil)
    }
}

也可以在这里看到:https://play.golang.org/p/gNUsANjuPV0

这总是会因为 .Call() 的参数太少而出现恐慌。我看不出这与此处的代码在结构上有何不同:https://play.golang.org/p/HB8yB91LRme

【问题讨论】:

  • 提示 1:在链接的示例中,该方法没有参数,但在“调用”中提供了一个参数。提示 2:请参阅“呼叫”的文档。

标签: go reflection


【解决方案1】:

要从类型调用方法,您必须传递一个reflect.Value 实例,该实例提供作为接收者的Foo 对象加上一个reflect.Value 实例它提供了每个函数接收的int 参数:

fooType := reflect.TypeOf(&Foo{})
fooVal := reflect.ValueOf(&Foo{})
fmt.Println("--- Calling methods ---")
for i := 0; i < fooType.NumMethod(); i++ {
    method := fooType.Method(i)
    arg := i + 10
    method.Func.Call([]reflect.Value{fooVal, reflect.ValueOf(arg)})
}

例如。请注意,如果您从 value 调用该方法,则接收器是通过该值提供的,因此我们可以删除第一个参数:

    arg = i + 20
    reflect.Indirect(fooVal).Method(i).Call([]reflect.Value{reflect.ValueOf(arg)})

complete example on Go playground——但请注意,我们只需要获取一次 foo 对象,在其方法的循环上方:https://play.golang.org/p/HHk_mO2KXc6,因此循环中的最后一行就是:

    fooObj.Method(i).Call([]reflect.Value{reflect.ValueOf(arg)})

【讨论】:

    猜你喜欢
    • 2013-05-29
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 2018-02-10
    相关资源
    最近更新 更多