【问题标题】:Can't get returning string value of a method called via reflection无法获取通过反射调用的方法的返回字符串值
【发布时间】:2016-01-06 18:47:56
【问题描述】:

无法获取通过反射调用的方法的返回字符串值

panic:接口转换:接口是[]reflect.Value,而不是字符串

package main

import (
        "reflect"
)

type API_EndPoint struct{}

func main() {

        var ep API_EndPoint
        s := reflect.ValueOf(&ep).MethodByName("EndPoint_X").Call([]reflect.Value{reflect.ValueOf(`foo bar`)})

        v := reflect.ValueOf(s)
        i := v.Interface()
        a := i.(string)

        println(a)

}

func (ep *API_EndPoint) EndPoint_X(params string) string {

        return "this_is_a_string" + params

}
see this code in play.golang.org

【问题讨论】:

    标签: go


    【解决方案1】:

    .Call 返回 slicereflect.Value 所以要执行您想要执行的操作,您需要执行以下操作:

    package main
    
    import ("reflect")
    
    type API_EndPoint struct {}
    
    func main() {
    
    var ep API_EndPoint
    s := reflect.ValueOf(&ep).MethodByName("EndPoint_X").Call([]reflect.Value{reflect.ValueOf(`foo bar`)})
    
    v := reflect.ValueOf(s)
    i := v.Interface()
    a := i.([]reflect.Value)[0].String() // Get the first index of the slice and call the .String() method on it
    
    println(a) 
    
    }
    
    func (ep *API_EndPoint) EndPoint_X( params string) string{
    
            return "this_is_a_string " + params
    
    }
    

    https://play.golang.org/p/MtqCrshTcH

    this_is_a_string foo bar

    不确定您要完成什么,但应该可以。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-04
      • 2012-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多