結論:
golang不支持解析string然后執行。
golang的反射機制只能存在於已經存在的對象上面。
不知道后續的版本有沒有規划,現在只能先加載注冊,然后實現類似Java工廠模式的反射。
代碼示例:
t := reflect.ValueOf(Human{}).Type() // h := reflect.New(t).Elem() // new return address pointer h := reflect.New(t).Interface() fmt.Println(h) hh := h.(*Human) fmt.Println(hh) hh.SayHello() hh.age = 123 hh.name = "abc" hh.weight = 345 hh.SayHello()
i = Human{"Emp", 25, 120}
fmt.Println(reflect.TypeOf(i).Field(0).Type)
fmt.Println(reflect.ValueOf(i).Field(1))
// reflect.ValueOf(i).Field(1).Elem().SetInt(88)
// fmt.Println(reflect.ValueOf(i).Field(1))
參考資料:
知乎,為什么不能通過字符串創建golang對象: https://www.zhihu.com/question/25580049
http://www.tuicool.com/articles/ZJBNni
https://my.oschina.net/wujibing/blog/682802
http://studygolang.com/articles/896
http://blog.csdn.net/rufidmx/article/details/18226649
http://www.cnblogs.com/yjf512/archive/2012/06/10/2544391.html