mardi 5 avril 2016

Reflection: Struct by string

Let's assume I have this struct with a method:

package main

import (
    "fmt"
    "reflect"
)

type MyStruct struct {
}

func (a *MyStruct) AAction() {
    fmt.Println("Hello a")
}

Now, if I want to call the method "AAction" by string, I can use reflection (this works):

func main() {
    reflect.New(reflect.TypeOf(MyStruct{})).MethodByName("AAction").Call([]reflect.Value{})
}

The problem is, that I don't want to use MyStruct{} as an expression, but as a string. Of course this doesn't work:

func main() {
    theStruct := "MyStruct"
    theAction := "AAction"
    reflect.New(reflect.TypeOf(theStruct)).MethodByName(theAction).Call([]reflect.Value{})
}

because reflect.Typeof(theStruct) would be a string. I tried reading through the documentation, sadly, I can't find anything very useful.

I found this similar question: Call a Struct and its Method by name in Go?
Under the accepted question, the OP asks:

The issue in my case Is I cant not declare t is typed T, its must be some how I can declare t typed T by the name of T is string "T"

which gets answered by

[...] I would suggest to match the name against the string "T" somewhere in your code [...]

which doesn't solve the problem, as I would still need to call MyStruct{} somewhere.

The question is: is there any way to use a struct by giving the name as a string? (without manually mapping the the name of the struct to the struct)

Working version with using reflect.TypeOf(MyStruct{}): http://ift.tt/1USCWBT Not working version, obviously calling the method on a string: http://ift.tt/23d5NBT





Aucun commentaire:

Enregistrer un commentaire