Golang struct动态调用其方法和属性

package main

import (
	"fmt"
	"reflect"
)

type MyStr1 struct {
}

func (y *MyStr1) Test1() {
	fmt.Println("Test1 called")
}

type MyStr2 struct {
}

func (y *MyStr2) Test2(i int, oo string) {
	fmt.Println("Test2 called", i, oo)
}

func DynamicInvoke(object interface{}, methodName string, args ...interface{}) {
	inputs := make([]reflect.Value, len(args))
	for i, _ := range args {
		inputs[i] = reflect.ValueOf(args[i])
	}
	//动态调用方法
	reflect.ValueOf(object).MethodByName(methodName).Call(inputs)

	//动态访问属性
	reflect.ValueOf(object).Elem().FieldByName("Name")
}

func main() {
	DynamicInvoke(new(MyStr1), "Test1")
	DynamicInvoke(new(MyStr2), "Test2", 5, "bbbb")
}

你可能感兴趣的:(Golang)