Golang 调用字符串函数名

Jackey Golang 1,465 次浏览 没有评论
package main

import (
    "fmt"
    "reflect"
)

type Animal struct {
    A string `json:"a"`
}

func (m *Animal) Eat()  {
    fmt.Println("eat", m.A)
}

func main()  {
    animal := Animal{
        A: "test",
    }
    value := reflect.ValueOf(&animal)
    f := value.MethodByName("Eat")
    f.Call([]reflect.Value{})
}

带参数:

package main

import (
    "fmt"
    "reflect"
)

type Animal struct {}

func (m *Animal) Eat(a string, i int)  {
    fmt.Println("eat", a, i)
}

func main()  {
    animal := Animal{}
    p := make([]reflect.Value, 2)
    p[0] = reflect.ValueOf("test")
    p[1] = reflect.ValueOf(1)
    reflect.ValueOf(&animal).MethodByName("Eat").Call(p)
}

带返回值:

package main

import (
    "fmt"
    "reflect"
)

type Animal struct{}

func (m *Animal) Eat(a string, i int) (string, int) {
    return a, i
}

func main() {
    animal := Animal{}
    p := make([]reflect.Value, 2)
    p[0] = reflect.ValueOf("test")
    p[1] = reflect.ValueOf(1)
    values := reflect.ValueOf(&animal).MethodByName("Eat").Call(p)
    for key, val := range values {
        fmt.Printf("%d:%v\n", key, val)
    }
}

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Go