通过Go反射,可以通过完整名称获取类型。

huangapple go评论81阅读模式
英文:

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]
}

huangapple
  • 本文由 发表于 2015年4月9日 16:34:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/29533602.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定