網站首頁 編程語言 正文
在使用reflect包獲取函數,并調用時,總出現這個報錯:
panic: reflect: call of reflect.Value.Call on zero Value
然后測試發現,只有公有函數(首字母大寫的函數)可以通過reflect.MethodByName()函數獲取,私有方法是不行的。
測試如下:
定義一個接口obj
objA實現接口。
為objA分配三個方法,兩個公有方法一個私有方法。
使用MethodByName()獲取函數并調用。
type obj interface { Do() } type objA struct { a []int b []int c int } var N int = 1000 func NewObjA() (o *objA) { o = &objA{} rand.Seed(time.Now().UnixNano()) o.a = make([]int, N) o.b = make([]int, N) for i := 0; i < N; i++ { o.a[i] = rand.Intn(256) o.b[i] = rand.Intn(256) } return } func (o *objA) Do() { o.c = 0 for i := range o.a { o.c += o.a[i] * o.b[i] % 256 } } func (o *objA) do() { o.c = 0 for i := range o.a { o.c += o.a[i] * o.b[i] % 256 } } func (o *objA) Do2() int{ o.c = 0 for i := range o.a { o.c += o.a[i] * o.b[i] % 256 } return o.c } func main() { a := obj(NewObjA()) v:=reflect.ValueOf(a) if f1 := v.MethodByName("Do"); f1.IsValid() { f1.Call([]reflect.Value{}) fmt.Println("成功執行 Do") } if f2 := v.MethodByName("do"); f2.IsValid() { f2.Call([]reflect.Value{}) fmt.Println("成功執行 do") } if f2 := v.MethodByName("Do2"); f2.IsValid() { f2.Call([]reflect.Value{}) fmt.Println("成功執行 Do2,結果 ") } fmt.Println("方法數量為:",v.NumMethod()) for i:=0;i< v.NumMethod();i++{ f:=v.Method(i) fmt.Println("方法",i,":",f.Type()) } }
運行結果:
發現只有兩個公有方法能夠執行
私有方法是沒有辦法獲取到的
原文鏈接:https://aikysay.blog.csdn.net/article/details/123554837
相關推薦
- 2022-04-24 redis用list做消息隊列的實現示例_Redis
- 2022-11-04 python使用tqdm模塊處理文件閱讀進度條顯示_python
- 2022-06-10 C#關鍵字Check簡單介紹_C#教程
- 2022-07-21 Gitee:使用ssh提交代碼卻提示:DeployKey does not support push
- 2022-05-26 Android?Flutter實現3D動畫效果示例詳解_Android
- 2022-11-13 使用git?checkout到歷史某個版本_相關技巧
- 2022-07-11 Python利用xlrd?與?xlwt?模塊操作?Excel_python
- 2022-11-30 詳解Python如何輕松實現定時執行任務_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支