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

猜你喜欢

转载自hhg08.iteye.com/blog/2283581