英文:
Is there a way to get the Type by full name using Go reflection?
问题
在Java中,可以通过Class.forName("com.my_pkg_name.MyClass")
来实现,它会返回类的类型。
似乎Go的反射只能通过值找到类型,但不允许通过名称找到类型。当实现与Go代码交互的脚本语言解释器时,这种能力非常有帮助。
英文:
In Java, it can be done by Class.forName("com.my_pkg_name.MyClass")
which returns the class type.
It seems Go reflection can only find the Type by Value but doesn't allow name to Type. This capability can be very helpful when implementing a scripting language interpreter which interops with Go code.
答案1
得分: 6
除非你明确注册类型,就像gob
包那样。类似于:
// 注意:应该由互斥锁保护。
var types map[string]reflect.Type
func Register(value interface{}) {
t := reflect.TypeOf(value)
name := t.PkgPath() + "." + t.Name()
types[name] = t
}
func TypeByName(name string) reflect.Type {
return types[name]
}
英文:
Not unless you explicitly register the type, like the gob
package does. Something like
// NOTE Should be protected by a mutex.
var types map[string]reflect.Type
func Register(value interface{}) {
t := reflect.TypeOf(value)
name := t.PkgPath() + "." + t.Name()
types[name] = t
}
func TypeByName(name string) reflect.Type {
return types[name]
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论