github.com/hedzr/evendeep@v0.4.8/internal/cl/field.go (about) 1 package cl 2 3 import ( 4 "reflect" 5 "unsafe" 6 7 "github.com/hedzr/evendeep/typ" 8 ) 9 10 // Field wraps a struct field with its type and value pair. 11 type Field struct { 12 Type reflect.StructField 13 Value reflect.Value 14 } 15 16 // GetUnexportedField returns the value of the unexported field. 17 func (field *Field) GetUnexportedField() typ.Any { 18 return GetUnexportedField(field.Value).Interface() 19 } 20 21 // SetUnexportedField puts a new value into the unexported field. 22 func (field *Field) SetUnexportedField(value typ.Any) { 23 SetUnexportedField(field.Value, reflect.ValueOf(value)) 24 } 25 26 // // GetUnexportedField return the value of the unexported field 27 // func GetUnexportedField(field reflect.Value) typ.Any { 28 // return getUnexportedField(field).Interface() 29 // } 30 31 // GetUnexportedField return the value of the unexported field. 32 func GetUnexportedField(field reflect.Value) reflect.Value { 33 return reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).Elem() 34 } 35 36 // // SetUnexportedField puts a new value into the unexported field 37 // func SetUnexportedField(field reflect.Value, value typ.Any) { 38 // setUnexportedField(field, reflect.ValueOf(value)) 39 // } 40 41 // SetUnexportedField puts a new value into the unexported field. 42 func SetUnexportedField(field, value reflect.Value) { 43 ptr := reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())) 44 dat := ptr.Elem() 45 dat.Set(value) 46 } 47 48 func SetUnexportedFieldIfMap(field, key, value reflect.Value) { 49 ptr := reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())) 50 dat := ptr.Elem() 51 if field.Kind() == reflect.Map { 52 dat.SetMapIndex(key, value) 53 } else { 54 dat.Set(value) 55 } 56 }