我想用golang实现一个基本的mvc, IndexController继承了mvc包中的Controller,但是在mvc包中用反射获取不到IndexController的GET()方法,搞了一天了不知道怎么解决!求高人指点!!!
package mvc
import (
"log"
"net/http"
"reflect"
)
type App struct{}
type Controller struct {
}
func (c *Controller) ServeHTTP(w http.ResponseWriter, r *http.Request) {
uc := reflect.ValueOf(c)
method := uc.MethodByName("GET")
methodValid := method.IsValid()
if methodValid == true {
log.Println("方法存在")
//method.Call([]reflect.Value{})
} else {
log.Println("方法不存在")
}
}
package main
import (
"log"
"net/http"
"test/mvc"
)
type IndexController struct {
mvc.Controller
}
func (c *IndexController) GET() {
log.Println("GET")
}
func main() {
http.Handle("/", &IndexController{})
http.ListenAndServe(":8100", nil)
}
反射的实质是调用类的编译文件,你父类的编译文件里是不可能存在子类的方法的。
你的代码我不太明白,但另一种方案是,可以用多态性,转型一下,用子类对象实例化父类,然后再调子类方法。
不一定是你想要的意思,也不一定能帮到你,但是以上两个解释是没有问题的。
楼上说的很对。
func (c *Controller) ServeHTTP(w http.ResponseWriter, r *http.Request) {
uc := reflect.ValueOf(c)
if uc.MethodByName("Person").IsValid(){
log.Println("方法存在")
//method.Call([]reflect.Value{})
} else {
log.Println("方法不存在")
}
}
func (c *Controller) Person(){
fmt.Println("person")
}
这样的话就能找到了