Skip to content

Instantly share code, notes, and snippets.

@ahmdrz
Created August 31, 2016 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmdrz/7d17d355d165269690a01a96a170c7dc to your computer and use it in GitHub Desktop.
Save ahmdrz/7d17d355d165269690a01a96a170c7dc to your computer and use it in GitHub Desktop.
func CallMethod(i interface{}, methodName string) interface{} {
var ptr reflect.Value
var value reflect.Value
var finalMethod reflect.Value
value = reflect.ValueOf(i)
if value.Type().Kind() == reflect.Ptr {
ptr = value
value = ptr.Elem()
} else {
ptr = reflect.New(reflect.TypeOf(i))
temp := ptr.Elem()
temp.Set(value)
}
method := value.MethodByName(methodName)
if method.IsValid() {
finalMethod = method
}
method = ptr.MethodByName(methodName)
if method.IsValid() {
finalMethod = method
}
if finalMethod.IsValid() {
return finalMethod.Call([]reflect.Value{})[0].Interface()
}
return ""
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment