douan8473 2018-01-07 08:45 采纳率: 100%
浏览 138
已采纳

反映(MethodByName)无效

Problem at reflection, with MethodByName

Code:

package main

import (
    "reflect"
    "fmt"
)

type test struct {}

var serviceType = map[string]reflect.Value{
    "test": reflect.ValueOf(test{}),
}

func (t *test) prnt()  {
    fmt.Println("test ok")
}

func callFunc(strct string, fName string)  {

    s := serviceType[strct].MethodByName(fName)
    if !s.IsValid(){
        fmt.Println("not correct")
        return
    }

    s.Call(make([]reflect.Value,0))
}

func main()  {
    callFunc("test", "prnt")
}

Output:

not correct

Playground: https://play.golang.org/p/ZLEQBGYoUOB

Could you help, what I'm doing wrong ?

  • 写回答

1条回答 默认 最新

  • duanfei1268 2018-01-07 09:06
    关注

    Two things needs to be corrected.

    1. MethodByName() returns only Exported methods. So you have to rename prnt tp Prnt
    2. Needs to pass a pointer of struct test to reflect.ValueOf() method.

    Here is the modified working code https://play.golang.org/p/4MK2kqOz6e2

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?