Skip to content

Instantly share code, notes, and snippets.

@huanghantao
Last active July 5, 2019 05:59
Show Gist options
  • Save huanghantao/33d7ad1e312a9b4932427cfcf9e55b0b to your computer and use it in GitHub Desktop.
Save huanghantao/33d7ad1e312a9b4932427cfcf9e55b0b to your computer and use it in GitHub Desktop.
存储反射类型以及执行存储的反射类型的方法
package main
import (
"fmt"
"reflect"
)
var typeRegistry = make(map[string]reflect.Type)
func registerType(typedNil interface{}) {
t := reflect.TypeOf(typedNil).Elem()
typeRegistry[t.PkgPath()+"."+t.Name()] = t
}
// S struct
type S struct {
A int
}
// Method1 的M一定要大写
func (s S) Method1() {
fmt.Println("method 1")
}
// Method2 的M一定要大写
func (s S) Method2() string {
return "method 2"
}
// Method3 的M一定要大写
func (s S) Method3(arg string) {
fmt.Println(arg)
}
func init() {
registerType((*S)(nil))
}
func makeInstance(name string) interface{} {
v := reflect.New(typeRegistry[name]).Elem()
// Maybe fill in fields here if necessary
return v.Interface()
}
func main() {
a := makeInstance("main.S")
aa := reflect.ValueOf(a)
var args []reflect.Value
m1 := aa.MethodByName("Method1")
m1.Call(nil)
m2 := aa.MethodByName("Method2")
res := m2.Call(nil)
fmt.Println(res[0])
m3 := aa.MethodByName("Method3")
args = []reflect.Value{reflect.ValueOf("wudebao")}
m3.Call(args)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment