2

The invocation of the method through the reflect object is divided into three steps:

  • Step 1: Get the reflection object through the interface variable (implemented through valueOf)
  • Step 2: Get the corresponding method object (which can be obtained through MathodByName())
  • The third step: call the method object: Call(), this function needs the parameter list required by the reflection object, and there is no slice that can be passed nil or empty.

The specific code example is as follows (including the cases of no parameter and parameter 2):

 package main

import (
    "fmt"
    "reflect"
)

type Person struct {
    Name   string
    Age    int
    Gender string
}

func (p Person) Say(msg string) {
    fmt.Println("hello, ", msg)
}

func (p Person) PrintInfo() {
    fmt.Printf("Name: %s, Age: %d, Gender: %s", p.Name, p.Age, p.Gender)
}
func main() {
    p1 := Person{"lokays", 19, "male"}
    value := reflect.ValueOf(p1)
    methodValue1 := value.MethodByName("PrintInfo")
    fmt.Printf("kind: %s, type: %s\n", methodValue1.Kind(), methodValue1.Type())

    //没有参数进行调用
    methodValue1.Call(nil)

    //有参数进行调用
    methodValue2 := value.MethodByName("Say")
    //这里的参数需要一个反射对象value类型的切片,说人话就是,这里需要把字符串转成反射对象
    args2 := []reflect.Value{reflect.ValueOf(":hey it's liber")}
    methodValue2.Call(args2)
}

The results are as follows:

 kind: func, type: func()
Name: lokays, Age: 19, Gender: malehello,  :hey it's liber

Reference: bilibili


LiberHome
409 声望1.1k 粉丝

有问题 欢迎发邮件 📩 liberhome@163.com