Skip to content

Instantly share code, notes, and snippets.

@NSEcho
Created March 31, 2021 22:24
Show Gist options
  • Save NSEcho/52b6661f9dae12183776ee46c5963588 to your computer and use it in GitHub Desktop.
Save NSEcho/52b6661f9dae12183776ee46c5963588 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"reflect"
)
func printMe(arg string) {
fmt.Println(arg)
}
func printMeAlso(arg string, age int) {
fmt.Println(arg)
fmt.Println(age)
}
type Person struct {
name string
age int
}
func (p *Person) PrintPerson() {
fmt.Printf("Name => %s\tAge => %d\n", p.name, p.age)
}
type Animal struct {
kind string
}
func (a *Animal) PrintAnimal() {
fmt.Printf("Kind => %s\n", a.kind)
}
func callSpecific(obj interface{}) {
if reflect.TypeOf(obj).Name() == "Person" {
fmt.Println("[*] Found Person, calling it's method")
newObj, _ := reflect.ValueOf(obj).Interface().(Person)
f := reflect.ValueOf(&newObj).MethodByName("PrintPerson")
f.Call([]reflect.Value{})
} else if reflect.TypeOf(obj).Name() == "Animal" {
fmt.Println("[*] Found Animal, calling it's method")
newObj, _ := reflect.ValueOf(obj).Interface().(Animal)
f := reflect.ValueOf(&newObj).MethodByName("PrintAnimal")
f.Call([]reflect.Value{})
}
}
func callFunc(fn interface{}, args ...interface{}) {
v := reflect.ValueOf(fn)
rargs := make([]reflect.Value, len(args))
for i, a := range args {
rargs[i] = reflect.ValueOf(a)
}
v.Call(rargs)
}
func main() {
callFunc(printMe, "aa")
callFunc(printMeAlso, "aaa", 20)
p := Person{"Erhad", 24}
a := Animal{"Dog"}
f := reflect.ValueOf(&p).MethodByName("PrintPerson")
f.Call([]reflect.Value{})
callSpecific(p)
callSpecific(a)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment