Go反射调用方法
来源:互联网 发布:黄金买卖交易软件 编辑:程序博客网 时间:2024/06/07 18:31
Go提供了一个很重要的特性就是反射机制,反射机制对应处理一些特殊的应用场景非常实用。下文是Go反射调用函数的代码片段。
type Test struct {}func (t *Test)PrintInfo(i int , s string) string{ fmt.Println("call method PrintInfo i", i, ",s :", s) return s +strconv.Itoa(i)}func (t *Test)ShowMsg() string { fmt.Println("\nshow msg input 'call reflect'") return "ShowMsg"}func callReflect(any interface{}, name string, args... interface{}) []reflect.Value{ inputs := make([]reflect.Value, len(args)) for i, _ := range args { inputs[i] = reflect.ValueOf(args[i]) } if v := reflect.ValueOf(any).MethodByName(name); v.String() == "<invalid Value>" { return nil }else { return v.Call(inputs) }}func callReflectMethod(){ fmt.Printf("\n callReflectMethod PrintInfo :%s", callReflect(&Test{}, "PrintInfo", 10, "TestMethod")[0].String()) fmt.Printf("\n callReflectMethod ShowMsg %s", callReflect(&Test{}, "ShowMsg")[0].String()) //<invalid Value> case callReflect(&Test{}, "ShowMs") if result := callReflect(&Test{}, "ShowMs"); result != nil { fmt.Printf("\n callReflectMethod ShowMs %s", result[0].String()) }else { fmt.Println("\n callReflectMethod ShowMs didn't run ") } fmt.Println("\n reflect all ")}
在main函数中调用函数callReflectMethod就可以运行上面代码片段了。
欢迎加入我的微信公众号
阅读全文
0 0
- Go反射调用方法
- go反射通过字符串调用方法
- go动态调用方法
- 反射:使用反射调用方法
- java反射调用方法
- 反射的调用方法
- Java反射调用方法
- 使用反射调用方法
- 反射调用main方法
- 利用反射调用方法
- 利用反射调用方法
- 用反射调用方法
- Java 反射 方法调用
- java 反射 方法调用
- java反射调用方法
- JAVA 反射调用方法
- 反射调用main方法
- 反射调用私有方法
- ubuntu下latex中文环境配置
- jpeg
- Python的namedtuple使用详解
- Latex 绘制立方交换图
- 孩子记忆力差原因可能在这里
- Go反射调用方法
- 基本的Material Design布局结构
- ajax跨域
- android 打Jar包和混淆配置
- 使用python解析xls生成lua配置
- spring bean的一些问题
- sql: unknown driver "mysql" (forgotten import?)
- 周报
- Linux下Mysql 5.6.21 tar包安装实践