【发布时间】:2019-12-05 13:19:43
【问题描述】:
我知道,有人问过类似的问题,但我没有找到该案例的答案:
type ExportedStruct struct{ //comes from a dependency, so I can't change it
unexportedResource ExportedType
}
我想在unexportedResource 上调用一个导出 方法Close()。
我所做的是:
rs := reflect.ValueOf(myExportedStructPtr).Elem() //myExportedStructPtr is a pointer to an ExportedStruct object
resourceField := rs.FieldByName("unexportedResource")
closeMethod := resourceField.MethodByName("Close")
closeMethod.Call([]reflect.Value{reflect.ValueOf(context.Background())})
,结果为reflect.flag.mustBeExported using value obtained using unexported field。
这很烦人,因为我想运行多个使用 ExportedStruct 的测试,但只要不使用底层资源,我就不能。
由于我可以访问私有字段(如 here 所解释的那样),我有点希望我也能以某种方式访问该字段的公共方法。也许我只是反映错了?
【问题讨论】:
标签: go methods reflection