如何使用反射获取任意方法签名?

我可以用额外的一双眼睛来解决这个挑战,这里是游乐场

最终目标是将函数和结构公共函数注册到活动管理器中,并通过函数名称执行它们,因此类似于:

  pool := map[string]interface{

       "Sample": func(ctx context.Context) error,

       "Sample2": func(ctx context.Context, args ...interface{}) error,

       "SampleFromStruct": func(ctx context.Context) error,

       "Sample2FromStruct": func(ctx context.Context, args ...interface{}) error,

   }

功能看起来像:


func Sample(ctx context.Context) error {

    fmt.Println("exec Sample")

    return nil

}


func Sample2(ctx context.Context, args interface{}) error {

    arguments := struct {

        Foo string `json:"foo"`

        Bar string `json:"bar"`

    }{


    b, err := json.Marshal(args)

    if err != nil {

        return err

    }


    if err := json.Unmarshal(b, &arguments); err != nil {

        return err

    }


    fmt.Println("exec Sample2 with args", arguments)


    return nil

}


// and same but with struct

type ActivityInStruct struct {

    Bar string

}


func (a *ActivityInStruct) SampleInStruct(ctx context.Context) error {

    fmt.Println("Value of Bar", a.Bar)

    return Sample(ctx)

}


func (a *ActivityInStruct) Sample2InStruct(ctx context.Context, args interface{}) error {

    fmt.Println("Value of Bar", a.Bar)

    return Sample2(ctx, args)

}


这么说,我得到了它与以下实现的功能一起使用:


type activityManager struct {

    fnStorage map[string]interface{}

}


func (lm *activityManager) Register(fn interface{}) error {

    fnName := strings.Split((runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name()), ".")

    name := fnName[len(fnName)-1]

    lm.fnStorage[name] = fn

    return nil

}




慕尼黑的夜晚无繁华
浏览 95回答 1
1回答

一只名叫tom的猫

调用Value.Method以获取方法值。func (lm *activityManager) RegisterStruct(fn interface{}) error {&nbsp; &nbsp; v := reflect.ValueOf(fn)&nbsp; &nbsp; t := v.Type()&nbsp; &nbsp; for i := 0; i < t.NumMethod(); i++ {&nbsp; &nbsp; &nbsp; &nbsp; m := t.Method(i)&nbsp; &nbsp; &nbsp; &nbsp; if m.IsExported() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lm.fnStorage[m.Name] = v.Method(i).Interface()&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return nil}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go