I'm trying to do something that I believe SHOULD be possible, but I haven't quite figured out how to do it. I'm trying to access a function by name (ie, string name) from another package, and then execute this as a function. Now, I know that if this were a receiver function on an object in that package, I could just do something like:
t := reflect.TypeOf(foo)
if t == nil {
return
}
m := t.MethodByName("Bar")
if m == nil {
return
}
m.Call([]reflect.Value{reflect.ValueOf(foo))})
Which would be the equivalent of calling foo.Bar()
. Now suppose that I want to do this with something that is NOT a receiver function? I can't find anything in reflect
that will allow me to find an arbitrary function from an arbitrary package by name. What I am able to do so far is:
import (
"fmt"
"go/importer"
)
func main() {
pkg, err := importer.Default().Import("time")
if err != nil {
return
}
scope := pkg.Scope()
durobj := scope.Lookup("ParseDuration")
if durobj != nil {
return
}
// Now I have an object corresponding to time.ParseDuration(). How do I invoke it???
}
Why am I trying to do this, you ask? I've got the following setup. I have package A
which defines type AA
, which is maintained by someone else. I have package B
which includes methods to transform type AA
, which I am a maintainer for. I already have several transformations defined in package B
. What I'm trying to do is set up, at runtime, the list of transformations execute. I have a robust means of entering the strings associated with the transformation function names at runtime. What I do not yet have is the means to look those function names up in package B
.
I understand that I could easily create a mapping in package B
to do this, but I'd rather not do that if I don't have to. It's OK if this is computationally intensive/non-performant, since we will not be making these changes frequently.
Thanks!
Aucun commentaire:
Enregistrer un commentaire