【GoLang】golang 如何像Java 一样通过类名反射对象?

结论:

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

 

posted @ 2016-11-29 18:28  junneyang  阅读(4803)  评论(0编辑  收藏  举报