reflect
Publish on 2024-09-19

什么是反射

在计算机科学中,反射是指计算机程序在运行时(Run time)可以访问、检测和修改它本身状态或行为的一种能力。用比喻来说,反射就是程序在运行的时候能够“观察”并且修改自己的行为。

难道不用反射就不能在运行时访问、检测和修改它本身的状态和行为吗?

问题的回答,其实要首先理解什么叫访问、检测和修改它本身状态或行为,它的本质是什么?

实际上,它的本质是程序在运行期探知对象的类型信息和内存结构。不用反射能行吗?可以的!使用汇编语言,直接和内层打交道,可以获取任何信息?但是,当编程迁移到高级语言上来之后,就不行了!只能通过反射来达到此项技能。

不同语言的反射模型不尽相同,有些语言还不支持反射。《Go 语言圣经》中是这样定义反射的:

Go 语言提供了一种机制在运行时更新变量和检查它们的值、调用它们的方法,但是在编译时并不知道这些变量的具体类型,这称为反射机制。

再挂一段摘自stackoverflow的解释

The first good example I can think of off the top of my head is for when you need to execute a set of methods on a given object without knowing at compile-time what methods will exist in it.

Take unit testing frameworks for example. The test runner class that is responsible for running all your unit tests doesn’t know ahead of time what you are going to name your methods. All it knows is that they will be prefixed with “test” (or in Java 5’s case, annotated with @Test). So when given a test class, it reflects on that class in order to get a list of all the methods in it. Then, it iterates through those method names as strings and calls those methods on the object if they start with “test”. That wouldn’t be possible without reflection. And that’s just one example.

什么时候需要反射

  1. 不能明确接口调用哪个函数,需要根据传入的参数在运行时决定。
  2. 不能明确传入函数的参数类型,需要在运行时处理任意对象。
  3. 彻底解耦调用者和执行者,执行者只负责执行,方法可以在运行时动态获取

为什么不推荐反射

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