如何使用反射创建参数化实体

how to using reflect to create parametric entity

package main

import (
    "fmt"
    "reflect"
)

type Aservice struct {
}

type Adata struct {
    msg string
}

type Bdata struct {
    more string
}

var amap map[string]interface{} = make(map[string]interface{}, 1024)

func (aser *Aservice) Bar(data *Adata) error {
    return nil
}

func (aser *Aservice) Foo(data *Bdata) error {
    return nil
}

func main() {
    var ser *Aservice
    typeOfService := reflect.TypeOf(ser)
    valueOfService := reflect.ValueOf(ser)

    for i := 0; i < valueOfService.NumMethod(); i++ {

        nref := valueOfService.Method(i).Type().In(0)
        fmt.Println("++", nref.Elem().Name())
        amap[typeOfService.Method(i).Name] = nref
    }
}

目前可以正确打印“Adata”和“Bdata”

但是我不知道如何在amap中存储“Adata”和“Bdata”的空结构指针

不知道下一步

我想在amap中使用Method(i).Name()来存储Method需要传入的参数

根据评论中的建议:

package main

import (
    "fmt"
    "reflect"
)

type Aservice struct {
}

type Adata struct {
    msg string
}

type Bdata struct {
    more string
}

var amap = map[string]interface{}{}

func (aser *Aservice) Bar(data *Adata) error {
    return nil
}

func (aser *Aservice) Foo(data *Bdata) error {
    return nil
}

func main() {
    var ser *Aservice
    typeOfService := reflect.TypeOf(ser)
    valueOfService := reflect.ValueOf(ser)

    for i := 0; i < valueOfService.NumMethod(); i++ {

        nref := valueOfService.Method(i).Type().In(0)
        amap[typeOfService.Method(i).Name] = reflect.New(nref.Elem()).Interface()
    }

    for k, v := range amap {
        fmt.Printf("%s %#v\n", k, v)
    }
}

输出:

Bar &main.Adata{msg:""}
Foo &main.Bdata{more:""}