go动态调用方法

本文介绍了一种在Go语言中动态调用接口方法的实现方式,通过反射获取并执行目标方法,支持指针和值类型的接收者。示例展示了如何为自定义结构体动态调用方法。
func CallMethod(i interface{}, methodName string) interface{} {
var ptr reflect.Value
var value reflect.Value
var finalMethod reflect.Value

value = reflect.ValueOf(i)

// if we start with a pointer, we need to get value pointed to
// if we start with a value, we need to get a pointer to that value
if value.Type().Kind() == reflect.Ptr {
ptr = value
value = ptr.Elem()
} else {
ptr = reflect.New(reflect.TypeOf(i))
temp := ptr.Elem()
temp.Set(value)
}

// check for method on value
method := value.MethodByName(methodName)
if method.IsValid() {
finalMethod = method
}
// check for method on pointer
method = ptr.MethodByName(methodName)
if method.IsValid() {
finalMethod = method
}

if (finalMethod.IsValid()) {
return finalMethod.Call([]reflect.Value{})[0].Interface()
}

// return or panic, method not found of either type
return ""
}


func (ubidreq *Ubidrequest) GetDid() (str_did string){
method_name := "Get"+CurrentMedia+"Did" //CurrentMidia == tencent
str_ret := CallMethod(ubidreq, method_name).(string)
return str_ret
}
某个地方定义了一个方法
func (ubidreq *Ubidrequest) GettencentDid() (string) {
................
}

第一个参数 方法的类型,第二个参数为方法的名。返回参数可以是.(string) .(bool) .([]string) 毕竟动态的方法返回的是一个interface{}

具体例子:
type Person struct{
Name string
Age int64
}

func (p *Person)GetName()(ret string){
ret = p.Name
return
}

func main() {
hhg := Person{"hhg08",222}
method_name := "Get"+"Name"
name := CallMethod(hhg,method_name).(string)
fmt.Println(name)
}
结果:
hhg08

http://stackoverflow.com/questions/14116840/dynamically-call-method-on-interface-regardless-of-receiver-type
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值