How to Invoke Methods with Reflection in Go

Use the reflect package's MethodByName and Call functions to dynamically invoke methods in Go.

Go does not have a built-in reflection API to invoke methods by name like Java or C#; instead, you use the reflect package to get a Method value and call its Call function. Use reflect.ValueOf to get the value, MethodByName to find the method, and Call with a slice of reflect.Value arguments to execute it.

import "reflect"

func invoke(obj any, methodName string, args ...any) any {
    v := reflect.ValueOf(obj)
    method := v.MethodByName(methodName)
    if !method.IsValid() {
        panic("method not found")
    }
    in := make([]reflect.Value, len(args))
    for i, arg := range args {
        in[i] = reflect.ValueOf(arg)
    }
    out := method.Call(in)
    if len(out) == 0 {
        return nil
    }
    return out[0].Interface()
}