Created
August 31, 2016 14:54
-
-
Save ahmdrz/7d17d355d165269690a01a96a170c7dc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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