woodings
woodings

Reputation: 7693

Is there a way to get the Type by full name using Go reflection?

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.

Upvotes: 2

Views: 836

Answers (1)

Ainar-G
Ainar-G

Reputation: 36199

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

Upvotes: 6

Related Questions