github.com/jmigpin/editor@v1.6.0/util/reflectutil/util.go (about) 1 package reflectutil 2 3 import ( 4 "fmt" 5 "reflect" 6 "strings" 7 ) 8 9 // only works with exported names (start with uppercase) 10 func InvokeByName(v interface{}, name string, args ...interface{}) ([]reflect.Value, error) { 11 method := reflect.ValueOf(v).MethodByName(name) 12 if method == (reflect.Value{}) { 13 return nil, fmt.Errorf("method not found: %v", name) 14 } 15 inputs := make([]reflect.Value, len(args)) 16 for i, _ := range args { 17 inputs[i] = reflect.ValueOf(args[i]) 18 } 19 return method.Call(inputs), nil 20 } 21 22 //---------- 23 24 // Useful to then call functions based on their type names. 25 func TypeNameBase(v interface{}) (string, error) { 26 rv := reflect.Indirect(reflect.ValueOf(v)) 27 if rv == (reflect.Value{}) { 28 return "", fmt.Errorf("typenamebase: zero value: %T", v) 29 } 30 // build name: get base string after last "." 31 ts := rv.Type().String() 32 if k := strings.LastIndex(ts, "."); k >= 0 { 33 ts = ts[k+1:] 34 } 35 return ts, nil 36 }