Can you give me an example of using that function?
From the called function point of view, it's just another call. No
special treatment here. So you don't have to do nothing special in the
Add function.
This works because you called MethodByName on a reflect.Value and not
in a reflect.Type, this way, the receiver is already defined.
> call the function MethodByName, with extra arguments?
You don't.
The MethodByName return the pointer to the function (bound to the &i object).
You pass the parameters in the add.Call method.
See: http://weekly.golang.org/pkg/reflect/#Value.Call
For each argument you need to pass, you add them to a []reflect.Value
slice and them pass the slice to add.Call
pseudo-code:
add := reflect.ValueOf(&i).MethodByName("Add")
a := int(0)
params := make([]reflect.Value,0)
params = append(params, reflect.ValueOf(a))
add.Call(params)
This will call the Add method passing the int "a" to it
--
André Moraes
http://andredevchannel.blogspot.com/
Why not just set up a map from strings to constructor functions and
use that?
Chris
(Yes, one could use reflection and seach for things of the right type and
go through the reflection API and and and and ... but why not go the
utterly straightforward route?)
Chris
--
Chris "allusive" Dollin
I already did something similar to that in one of my projects.
I can sent you the source code when I get home for lunch.
But the road is:
Get access to the type of the handler, the easy way is to pass a
zero-value of the hadler &MyHandler{} and find the type using reflect.
Associate the Type object with an String inside a Map.
Then, when receiving the request, create a new instace of the Type and
call the desired Method.
// this method return a function that any time is called (with
http.Request and ResponseWriter)
// will create a new instance with the same type as "sample" parameter
// and invoke the "method"
func RestDispatchMeth(sample interface{}, method string) http.HandlerFunc {
t := reflect.ValueOf(sample).Type()
return func(w http.ResponseWriter, req *http.Request) {
v := reflect.New(t)
log.Printf("Controller: %v", t.Name())
callControllerMethod(method, v, w, req)
}
}
// this function receiveis the controler "cont" and the "methodName" parameters
// together with the ResponseWriter and Request
// If it is able to find the method it call's the method.
func callControllerMethod(methodName string, cont reflect.Value, w
http.ResponseWriter, req *http.Request) {
// check if the method is valid
if method := cont.MethodByName(methodName); method.IsValid() {
vw := reflect.ValueOf(w)
vreq := reflect.ValueOf(req)
log.Printf("Method: %v", methodName)
// call it with the rigth parameters.
method.Call([]reflect.Value{0: vw, 1: vreq})
// Calls the after request handler
// If one is defined
if AfterRequest != nil {
AfterRequest.ServeHTTP(w, req)
}
} else {
log.Printf("Unable to find method: %v", methodName)