github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/isc/struct.go (about)

     1  package isc
     2  
     3  import (
     4  	"reflect"
     5  	"unsafe"
     6  )
     7  
     8  // 获取对象的属性:一般用于访问私有属性
     9  func GetPrivateFieldValue(objPtrValue reflect.Value, fieldName string) interface{} {
    10  	if objPtrValue.Kind() != reflect.Ptr {
    11  		return nil
    12  	}
    13  	fieldValue := objPtrValue.Elem().FieldByName(fieldName)
    14  	return reflect.NewAt(fieldValue.Type(), unsafe.Pointer(fieldValue.UnsafeAddr())).Elem().Interface()
    15  }
    16  
    17  // 给对象的属性设置值:一般用于设置私有属性
    18  func SetFieldPrivateValue(objPtrValue reflect.Value, fieldName string, fieldNewValue reflect.Value) {
    19  	if objPtrValue.Kind() != reflect.Ptr {
    20  		return
    21  	}
    22  	fieldValue := objPtrValue.Elem().FieldByName(fieldName)
    23  	fieldValue = reflect.NewAt(fieldValue.Type(), unsafe.Pointer(fieldValue.UnsafeAddr())).Elem()
    24  	fieldValue.Set(fieldNewValue.Elem())
    25  }