[golang]call method with reflection

package main

import (
	"reflect"
	"fmt"
)

type Ax struct {
	X int
}

type By struct {
	Y int
}

type Handler struct {

}

func (h *Handler) Add(ax Ax,bx By) int {
	return ax.X+bx.Y
}

func main()  {
	handler:=new(Handler)
	_,found1:=reflect.TypeOf(handler).MethodByName("Add")
	fmt.Println(found1)
	_,found2:=reflect.TypeOf(handler).MethodByName("Add2")
	fmt.Println(found2)
	method:=reflect.ValueOf(handler).MethodByName("Add")
	numIn:=method.Type().NumIn()
	fmt.Println(numIn)
	numOut:=method.Type().NumOut()
	fmt.Println(numOut)
	objects:=map[reflect.Type]interface{}{}
	objects[reflect.TypeOf(Ax{})]=Ax{10}
	objects[reflect.TypeOf(By{})]=By{20}
	in:=make([]reflect.Value,numIn)
	for i:=0; i<numIn; i++ {
		t:=method.Type().In(i)
		fmt.Println(t)
		object:=objects[t]
		in[i]=reflect.ValueOf(object)
	}
	for i:=0; i<numOut; i++ {
		t:=method.Type().Out(i)
		fmt.Println(t)
	}
	r:=method.Call(in)
	z:=r[0].Int()
	fmt.Print(z)
}

 

展开阅读全文

没有更多推荐了,返回首页