Last active
July 5, 2019 05:59
-
-
Save huanghantao/33d7ad1e312a9b4932427cfcf9e55b0b to your computer and use it in GitHub Desktop.
存储反射类型以及执行存储的反射类型的方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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