#how to call reflected method

6 messages · Page 1 of 1 (latest)

light patio
#

I have this code ```go
func (c *Client) UpdateAddon() {
println("addon received")
}

func (c *Client) Update(data map[string]any) {
for key := range data {
self := reflect.ValueOf(c)
name := fmt.Sprintf("Update%s", strings.Title(key))
method := self.MethodByName(name)
if method.IsZero() {
continue
}
args := []reflect.Value{}
method.Call(args) // should call UpdateAddon on key addon. For now panics.
}
}

#

On addon key it panic with reflect: call of reflect.Value.IsZero on zero Value

violet heath
#

Use method.IsValid() instead of IsZero. It's confusing but a zero value isn't a valid value and IsZero check if a valid value is zero. I don't know you understand the difference I explained here?

light patio
#

It correctly get to the line method.Call(args) and then panic with reflect: call of reflect.Value.IsZero on zero Value

violet heath
#

I wrote a minimal working example and it doesn't panic:

package main

import (
    "fmt"
    "reflect"
    "strings"
)

type Client struct {
}

func (c *Client) UpdateAddon() {
    println("addon received")
}

func (c *Client) Update(data map[string]any) {
    for key := range data {
        self := reflect.ValueOf(c)
        name := fmt.Sprintf("Update%s", strings.Title(key))
        method := self.MethodByName(name)
        if !method.IsValid() {
            continue
        }
        args := make([]reflect.Value, 0)
        method.Call(args) // should call `UpdateAddon` on key `addon`. For now panics.
    }
}

func main() {
    c := &Client{}
    c.Update(map[string]any{
        "Addon":    1,
        "sljglosg": 2,
    })
}