jeudi 5 décembre 2019

Calling an exported method on a unexported field

I know, similar questions have been asked, but I found no answer for that case:

type ExportedStruct struct{
  unexportedResource ExportedType
}

I want to call an exported method Close() on unexportedResource.

What I did was:

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())})

, which results in reflect.flag.mustBeExported using value obtained using unexported field.

This is quite annoying since I want to run more than one test which utilizes ExportedStruct, but I can't as long as the underlying resource is not used.

Since I can access private fields (as explained here) I have a bit hope that I'm allowed to access the public method of that field somehow, too. Maybe I'm just reflecting wrong?





Aucun commentaire:

Enregistrer un commentaire