首页 > 其他 > 详细

golang动态调用方法

时间:2014-09-16 14:06:20      阅读:441      评论:0      收藏:0      [点我收藏+]
package main

import (
    "fmt"
    "reflect"
)

type YourT1 struct {
}

func (y *YourT1) MethodBar() {
    fmt.Println("MethodBar called")
}

type YourT2 struct {
}

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

func InvokeObjectMethod(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)
}

func main() {
    InvokeObjectMethod(new(YourT2), "MethodFoo", 10, "abc")
    InvokeObjectMethod(new(YourT1), "MethodBar")
}

 

golang动态调用方法

原文:http://www.cnblogs.com/ziyouchutuwenwu/p/3974754.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!