广告位联系
返回顶部
分享到

Golang 中反射的应用实例介绍

Golang 来源:互联网 作者:佚名 发布时间:2022-08-26 10:58:17 人浏览
摘要

引言 首先来一段简单的代码逻辑热身,下面的代码大家觉得应该会打印什么呢? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 type OKR struct { id i

引言

首先来一段简单的代码逻辑热身,下面的代码大家觉得应该会打印什么呢?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

type OKR struct {

   id      int

   content string

}

func getOkrDetail(ctx context.Context, okrId int) (*OKR, *okrErr.OkrErr) {

   return &OKR{id: okrId, content: fmt.Sprint(rand.Int63())}, nil

}

func getOkrDetailV2(ctx context.Context, okrId int) (*OKR, okrErr.OkrError) {

   if okrId == 2{

      return nil, okrErr.OKRNotFoundError

   }

   return &OKR{id: okrId, content: fmt.Sprint(rand.Int63())}, nil

}

func paperOkrId(ctx context.Context) (int, error){

   return 1, nil

}

func Test001(ctx context.Context) () {

   var okr *OKR

   okrId, err := paperOkrId(ctx)

   if err != nil{

      fmt.Println("####   111   ####")

   }

   okr, err = getOkrDetail(ctx, okrId)

   if err != nil {

      fmt.Println("####   222   ####")

   }

   okr, err = getOkrDetailV2(ctx, okrId)

   if err != nil {

      fmt.Println("####   333   ####")

   }

   okr, err = getOkrDetailV2(ctx, okrId + 1)

   if err != nil {

      fmt.Println("####   444   ####")

   }

   fmt.Println("####   555   ####")

   fmt.Printf("%v", okr)

}

func main() {

   Test001(context.Background())

}

Golang类型设计原则

在讲反射之前,先来看看 Golang 关于类型设计的一些原则

  • 在 Golang 中变量包括(type, value)两部分
  • 理解这一点就能解决上面的简单问题了
  • type 包括 static type 和 concrete type. 简单来说 static type 是你在编码是看见的类型(如 int、string),concrete type 是 runtime 系统看见的类型。类型断言能否成功,取决于变量的 concrete type,而不是 static type.

接下来要说的反射,就是能够在运行时更新变量和检查变量的值、调用变量的方法和变量支持的内在操作,而不需要在编译时就知道这些变量的具体类型。这种机制被称为反射。Golang 的基础类型是静态的(也就是指定 int、string 这些的变量,它的 type 是 static type),在创建变量的时候就已经确定,反射主要与 Golang 的 interface 类型相关(它的 type 是 concrete type),只有运行时 interface 类型才有反射一说。

Golang 中为什么要使用反射/什么场景可以(应该)使用反射

当程序运行时, 我们获取到一个 interface 变量, 程序应该如何知道当前变量的类型,和当前变量的值呢?

当然我们可以有预先定义好的指定类型, 但是如果有一个场景是我们需要编写一个函数,能够处理一类共性逻辑的场景,但是输入类型很多,或者根本不知道接收参数的类型是什么,或者可能是没约定好;

也可能是传入的类型很多,这些类型并不能统一表示。

这时反射就会用的上了,典型的例子如:json.Marshal。

再比如说有时候需要根据某些条件决定调用哪个函数,比如根据用户的输入来决定。这时就需要对函数和函数的参数进行反射,在运行期间动态地执行函数。

举例场景:

比如我们需要将一个 struct 执行某种操作(用格式化打印代替),这种场景下我们有多种方式可以实现,比较简单的方式是:switch case

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

func Sprint(x interface{}) string {

    type stringer interface {

        String() string

    }

    switch x := x.(type) {

    case stringer:

        return x.String()

    case string:

        return x

    case int:

        return strconv.Itoa(x)

    // int16, uint32...

    case bool:

        if x {

            return "true"

        }

        return "false"

    default:

        return "wrong parameter type"

    }

}

type permissionType int64

但是这种简单的方法存在一个问题, 当增加一个场景时,比如需要对 slice 支持,则需要在增加一个分支,这种增加是无穷无尽的,每当我需要支持一种类型,哪怕是自定义类型, 本质上是 int64 也仍然需要增加一个分支。

反射的基本用法

在 Golang 中为我们提供了两个方法,分别是 reflect.ValueOf  和 reflect.TypeOf,见名知意这两个方法分别能帮我们获取到对象的值和类型。Valueof 返回的是 Reflect.Value 对象,是一个 struct,而 typeof 返回的是 Reflect.Type 是一个接口。我们只需要简单的使用这两个进行组合就可以完成多种功能。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

type GetOkrDetailResp struct {

   OkrId   int64

   UInfo   *UserInfo

   ObjList []*ObjInfo

}

type ObjInfo struct {

   ObjId int64

   Content string

}

type UserInfo struct {

   Name         string

   Age          int

   IsLeader     bool

   Salary       float64

   privateFiled int

}

// 利用反射创建struct

func NewUserInfoByReflect(req interface{})*UserInfo{

  if req == nil{

    return nil

  }

   reqType :=reflect.TypeOf(req)

  if reqType.Kind() == reflect.Ptr{

      reqType = reqType.Elem()

   }

   return reflect.New(reqType).Interface().(*UserInfo)

}

// 修改struct 字段值

func ModifyOkrDetailRespData(req interface{}) {

   reqValue :=reflect.ValueOf(req).Elem()

   fmt.Println(reqValue.CanSet())

   uType := reqValue.FieldByName("UInfo").Type().Elem()

   fmt.Println(uType)

   uInfo := reflect.New(uType)

   reqValue.FieldByName("UInfo").Set(uInfo)

}

// 读取 struct 字段值,并根据条件进行过滤

func FilterOkrRespData(reqData interface{}, objId int64){

// 首先获取req中obj slice 的value

for i := 0 ; i < reflect.ValueOf(reqData).Elem().NumField(); i++{

      fieldValue := reflect.ValueOf(reqData).Elem().Field(i)

if fieldValue.Kind() != reflect.Slice{

continue

      }

      fieldType := fieldValue.Type() // []*ObjInfo

      sliceType := fieldType.Elem() // *ObjInfo

      slicePtr := reflect.New(reflect.SliceOf(sliceType)) // 创建一个指向 slice 的指针

      slice := slicePtr.Elem()

      slice.Set(reflect.MakeSlice(reflect.SliceOf(sliceType), 0, 0))  // 将这个指针指向新创建slice

// 过滤所有objId == 当前objId 的struct

for i := 0 ;i < fieldValue.Len(); i++{

if fieldValue.Index(i).Elem().FieldByName("ObjId").Int() != objId {

continue

         }

         slice = reflect.Append(slice, fieldValue.Index(i))

      }

// 将resp 的当前字段设置为过滤后的slice

      fieldValue.Set(slice)

   }

}

func Test003(){

// 利用反射创建一个新的对象

var uInfo *UserInfo

   uInfo = NewUserInfoByReflect(uInfo)

   uInfo = NewUserInfoByReflect((*UserInfo)(nil))

// 修改resp 返回值里面的 user info 字段(初始化)

   reqData1 := new(GetOkrDetailResp)

   fmt.Println(reqData1.UInfo)

   ModifyOkrDetailRespData(reqData1)

   fmt.Println(reqData1.UInfo)

// 构建请求参数

   reqData := &GetOkrDetailResp{OkrId: 123}

   for i := 0; i < 10; i++{

      reqData.ObjList = append(reqData.ObjList, &ObjInfo{ObjId: int64(i), Content: fmt.Sprint(i)})

   }

// 输出过滤前结果

   fmt.Println(reqData)

// 对respData进行过滤操作

   FilterOkrRespData(reqData, 6)

// 输出过滤后结果

   fmt.Println(reqData)

}

反射的性能分析与优缺点

大家都或多或少听说过反射性能偏低,使用反射要比正常调用要低几倍到数十倍,不知道大家有没有思考过反射性能都低在哪些方面,我先做一个简单分析,通过反射在获取或者修改值内容时,多了几次内存引用,多绕了几次弯,肯定没有直接调用某个值来的迅速,这个是反射带来的固定性能损失,还有一方面的性能损失在于,结构体类型字段比较多时,要进行遍历匹配才能获取对应的内容。

下面就根据反射具体示例来分析性能:

测试反射结构体初始化

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

// 测试结构体初始化的反射性能

func Benchmark_Reflect_New(b *testing.B) {

   var tf *TestReflectField

   t := reflect.TypeOf(TestReflectField{})

   for i := 0; i < b.N; i++ {

      tf = reflect.New(t).Interface().(*TestReflectField)

   }

   _ = tf

}

// 测试结构体初始化的性能

func Benchmark_New(b *testing.B) {

   var tf *TestReflectField

   for i := 0; i < b.N; i++ {

      tf = new(TestReflectField)

   }

   _ = tf

}

运行结果:

可以看出,利用反射初始化结构体和直接使用创建 new 结构体是有性能差距的,但是差距不大,不到一倍的性能损耗,看起来对于性能来说损耗不是很大,可以接受。

测试结构体字段读取/赋值

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

// ---------    ------------  字段读  ----------- ----------- -----------

// 测试反射读取结构体字段值的性能

func Benchmark_Reflect_GetField(b *testing.B) {

   var tf = new(TestReflectField)

   var r int64

   temp := reflect.ValueOf(tf).Elem()

   for i := 0; i < b.N; i++ {

      r = temp.Field(1).Int()

   }

   _ = tf

   _ = r

}

// 测试反射读取结构体字段值的性能

func Benchmark_Reflect_GetFieldByName(b *testing.B) {

   var tf = new(TestReflectField)

   temp := reflect.ValueOf(tf).Elem()

   var r int64

   for i := 0; i < b.N; i++ {

      r = temp.FieldByName("Age").Int()

   }

   _ = tf

   _ = r

}

// 测试结构体字段读取数据的性能

func Benchmark_GetField(b *testing.B) {

   var tf = new(TestReflectField)

   tf.Age = 1995

   var r int

   for i := 0; i < b.N; i++ {

      r = tf.Age

   }

   _ = tf

   _ = r

}

// ---------    ------------  字段写  ----------- ----------- -----------

// 测试反射设置结构体字段的性能

func Benchmark_Reflect_Field(b *testing.B) {

   var tf = new(TestReflectField)

   temp := reflect.ValueOf(tf).Elem()

   for i := 0; i < b.N; i++ {

      temp.Field(1).SetInt(int64(25))

   }

   _ = tf

}

// 测试反射设置结构体字段的性能

func Benchmark_Reflect_FieldByName(b *testing.B) {

   var tf = new(TestReflectField)

   temp := reflect.ValueOf(tf).Elem()

   for i := 0; i < b.N; i++ {

      temp.FieldByName("Age").SetInt(int64(25))

   }

   _ = tf

}

// 测试结构体字段设置的性能

func Benchmark_Field(b *testing.B) {

   var tf = new(TestReflectField)

   for i := 0; i < b.N; i++ {

      tf.Age = i

   }

   _ = tf

}

测试结果:

从上面可以看出,通过反射进行 struct 字段读取耗时是直接读取耗时的百倍。直接对实例变量进行赋值每次 0.5 ns,性能是通过反射操作实例指定位置字段的10 倍左右。

使用 FieldByName("Age") 方法性能比使用 Field(1) 方法性能要低十倍左右,看代码的话我们会发现,FieldByName 是通过遍历匹配所有的字段,然后比对字段名称,来查询其在结构体中的位置,然后通过位置进行赋值,所以性能要比直接使用 Field(index) 低上很多。

建议:

  • 如果不是必要尽量不要使用反射进行操作, 使用反射时要评估好引入反射对接口性能的影响。
  • 减少使用 FieldByName 方法。在需要使用反射进行成员变量访问的时候,尽可能的使用成员的序号。如果只知道成员变量的名称的时候,看具体代码的使用场景,如果可以在启动阶段或在频繁访问前,通过 TypeOf() 、Type.FieldByName() 和 StructField.Index 得到成员的序号。注意这里需要的是使用的是 reflect.Type 而不是 reflect.Value,通过 reflect.Value 是得不到字段名称的。

测试结构体方法调用

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

// 测试通过结构体访问方法性能

func BenchmarkMethod(b *testing.B) {

   t := &TestReflectField{}

   for i := 0; i < b.N; i++ {

      t.Func0()

   }

}

// 测试通过序号反射访问无参数方法性能

func BenchmarkReflectMethod(b *testing.B) {

   v := reflect.ValueOf(&TestReflectField{})

   for i := 0; i < b.N; i++ {

      v.Method(0).Call(nil)

   }

}

// 测试通过名称反射访问无参数方法性能

func BenchmarkReflectMethodByName(b *testing.B) {

   v := reflect.ValueOf(&TestReflectField{})

   for i := 0; i < b.N; i++ {

      v.MethodByName("Func0").Call(nil)

   }

}

// 测试通过反射访问有参数方法性能

func BenchmarkReflectMethod_WithArgs(b *testing.B) {

   v := reflect.ValueOf(&TestReflectField{})

   for i := 0; i < b.N; i++ {

      v.Method(1).Call([]reflect.Value{reflect.ValueOf(i)})

   }

}

// 测试通过反射访问结构体参数方法性能

func BenchmarkReflectMethod_WithArgs_Mul(b *testing.B) {

   v := reflect.ValueOf(&TestReflectField{})

   for i := 0; i < b.N; i++ {

      v.Method(2).Call([]reflect.Value{reflect.ValueOf(TestReflectField{})})

   }

}

// 测试通过反射访问接口参数方法性能

func BenchmarkReflectMethod_WithArgs_Interface(b *testing.B) {

   v := reflect.ValueOf(&TestReflectField{})

   for i := 0; i < b.N; i++ {

      var tf TestInterface = &TestReflectField{}

      v.Method(3).Call([]reflect.Value{reflect.ValueOf(tf)})

   }

}

// 测试访问多参数方法性能

func BenchmarkMethod_WithManyArgs(b *testing.B) {

   s := &TestReflectField{}

   for i := 0; i < b.N; i++ {

      s.Func4(i, i, i, i, i, i)

   }

}

// 测试通过反射访问多参数方法性能

func BenchmarkReflectMethod_WithManyArgs(b *testing.B) {

   v := reflect.ValueOf(&TestReflectField{})

   va := make([]reflect.Value, 0)

   for i := 1; i <= 6; i++ {

      va = append(va, reflect.ValueOf(i))

   }

   for i := 0; i < b.N; i++ {

      v.Method(4).Call(va)

   }

}

// 测试访问有返回值的方法性能

func BenchmarkMethod_WithResp(b *testing.B) {

   s := &TestReflectField{}

   for i := 0; i < b.N; i++ {

      _ = s.Func5()

   }

}

// 测试通过反射访问有返回值的方法性能

func BenchmarkReflectMethod_WithResp(b *testing.B) {

   v := reflect.ValueOf(&TestReflectField{})

   for i := 0; i < b.N; i++ {

      _ = v.Method(5).Call(nil)[0].Int()

   }

}

这个测试结果同上面的分析相同

优缺点

优点:

  • 反射提高了程序的灵活性和扩展性,降低耦合性,提高自适应能力。
  • 合理利用反射可以减少重复代码

缺点:

  • 与反射相关的代码,经常是难以阅读的。在软件工程中,代码可读性也是一个非常重要的指标。
  • Go 语言作为一门静态语言,编码过程中,编译器能提前发现一些类型错误,但是对于反射代码是无能为力的。所以包含反射相关的代码,很可能会运行很久,才会出错,这时候经常是直接 panic,可能会造成严重的后果。
  • 反射对性能影响还是比较大的,比正常代码运行速度慢一到两个数量级。所以,对于一个项目中处于运行效率关键位置的代码,尽量避免使用反射特性。

反射在 okr 中的简单应用

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

func OkrBaseMW(next endpoint.EndPoint) endpoint.EndPoint {

   return func(ctx context.Context, req interface{}) (resp interface{}, err error) {

      if req == nil {

         return next(ctx, req)

      }

      requestValue := reflect.ValueOf(req)

      // 若req为指针,则转换为非指针值

      if requestValue.Type().Kind() == reflect.Ptr {

         requestValue = requestValue.Elem()

      }

      // 若req的值不是一个struct,则不注入

      if requestValue.Type().Kind() != reflect.Struct {

         return next(ctx, req)

      }

      if requestValue.IsValid() {

         okrBaseValue := requestValue.FieldByName("OkrBase")

         if okrBaseValue.IsValid() &amp;&amp; okrBaseValue.Type().Kind() == reflect.Ptr {

            okrBase, ok := okrBaseValue.Interface().(*okrx.OkrBase)

            if ok {

               ctx = contextWithUserInfo(ctx, okrBase)

               ctx = contextWithLocaleInfo(ctx, okrBase)

               ctx = contextWithUserAgent(ctx, okrBase)

               ctx = contextWithCsrfToken(ctx, okrBase)

               ctx = contextWithReferer(ctx, okrBase)

               ctx = contextWithXForwardedFor(ctx, okrBase)

               ctx = contextWithHost(ctx, okrBase)

               ctx = contextWithURI(ctx, okrBase)

               ctx = contextWithSession(ctx, okrBase)

            }

         }

      }

      return next(ctx, req)

   }

}

结论

使用反射必定会导致性能下降,但是反射是一个强有力的工具,可以解决我们平时的很多问题,比如数据库映射、数据序列化、代码生成场景。

在使用反射的时候,我们需要避免一些性能过低的操作,例如使用 FieldByName() 和MethodByName() 方法,如果必须使用这些方法的时候,我们可以预先通过字段名或者方法名获取到对应的字段序号,然后使用性能较高的反射操作,以此提升使用反射的性能。


版权声明 : 本文内容来源于互联网或用户自行发布贡献,该文观点仅代表原作者本人。本站仅提供信息存储空间服务和不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权, 违法违规的内容, 请发送邮件至2530232025#qq.cn(#换@)举报,一经查实,本站将立刻删除。
原文链接 : https://juejin.cn/post/7134962503657717773
相关文章
  • 基于GORM实现CreateOrUpdate的方法
    CreateOrUpdate 是业务开发中很常见的场景,我们支持用户对某个业务实体进行创建/配置。希望实现的 repository 接口要达到以下两个要求: 如果
  • Golang中的内存逃逸的介绍
    什么是内存逃逸分析 内存逃逸分析是go的编译器在编译期间,根据变量的类型和作用域,确定变量是堆上还是栈上 简单说就是编译器在编译
  • Golang自旋锁的介绍
    自旋锁 获取锁的线程一直处于活跃状态,但是并没有执行任何有效的任务,使用这种锁会造成busy-waiting。 它是为实现保护共享资源而提出的
  • Go语言读写锁RWMutex的源码

    Go语言读写锁RWMutex的源码
    在前面两篇文章中初见 Go Mutex、Go Mutex 源码详解,我们学习了Go语言中的Mutex,它是一把互斥锁,每次只允许一个goroutine进入临界区,可以保
  • Go项目实现优雅关机与平滑重启功能
    什么是优雅关机? 优雅关机就是服务端关机命令发出后不是立即关机,而是等待当前还在处理的请求全部处理完毕后再退出程序,是一种对
  • Go语言操作Excel利器之excelize类库的介绍
    在开发中一些需求需要通过程序操作excel文档,例如导出excel、导入excel、向excel文档中插入图片、表格和图表等信息,使用Excelize就可以方便
  • 利用Go语言快速实现一个极简任务调度系统

    利用Go语言快速实现一个极简任务调度系统
    任务调度(Task Scheduling)是很多软件系统中的重要组成部分,字面上的意思是按照一定要求分配运行一些通常时间较长的脚本或程序。在爬
  • GoLang中的iface 和 eface 的区别介绍

    GoLang中的iface 和 eface 的区别介绍
    GoLang之iface 和 eface 的区别是什么? iface和eface都是 Go 中描述接口的底层结构体,区别在于iface描述的接口包含方法,而eface则是不包含任何方
  • Golang接口使用的教程
    go语言并没有面向对象的相关概念,go语言提到的接口和java、c++等语言提到的接口不同,它不会显示的说明实现了接口,没有继承、子类、
  • go colly 爬虫实现示例介绍
    贡献某CC,go源码爬虫一个,基于colly,效果是根据输入的浏览器cookie及excel必要行列号,从excel中读取公司名称,查询公司法人及电话号码。
  • 本站所有内容来源于互联网或用户自行发布,本站仅提供信息存储空间服务,不拥有版权,不承担法律责任。如有侵犯您的权益,请您联系站长处理!
  • Copyright © 2017-2022 F11.CN All Rights Reserved. F11站长开发者网 版权所有 | 苏ICP备2022031554号-1 | 51LA统计