猴子修补/类重新开放真的是反射的例子吗?
对这个问题的递归性质表示歉意,但是 对一个问题的选择答案让我质疑我对反思的理解。
我认为反射主要是查询程序运行时的内部发生的情况。 此响应中给出的示例修补了 Ruby 的内置 Integer 类。
- 这不是更像函数重载/继承而不是运行时修改吗?
- 重新开课真的是反思的例子吗?
Apologies for the recursive nature of this question but the chosen answer to a question on SO got me questioning my understanding of reflection.
I thought reflection was mainly about querying the internal happenings of a program while it's running. The example given in this response patches Ruby's built-in Integer class.
- Isn't this more like function overloading/inheritance rather than runtime modification?
- Is class reopening really an example of reflection?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
反射可用于实现后期绑定。
后期绑定可用于实现猴子修补。
猴子修补可用于实现该答案中所示的编码风格。
但是还有其他方法可以实现此类功能,不需要猴子修补或反射。 哎呀,一个好的宏预编译器可以让你接近。
所以,技术上是正确的,但不是(恕我直言)最好的例子。
Reflection can be used to implement late binding.
Late binding can be used to implement monkey patching.
Monkey patching can be used to achieve the sort of coding style shown in that answer.
But there are other ways to implement such features that don't require monkey patching, or reflection. Heck, a good macro pre-compiler could get you close.
So, technically correct, but not (IMHO) the greatest example.
尽管您在该链接中引用了我的答案,但冒着增加递归级别的风险,我想做出回应。
这种误解很容易产生,因为我们对反思的直觉理解是指向内看。 这当然也是编程中反射的一个重要方面 - 例如,在 Ruby 中,我们有像 instance_of 这样的方法,允许对象在运行时询问有关自身的问题。
但请看一下维基百科对反射的定义:
正如您所看到的,反射不仅仅是运行时自我检查。 它还具有更改运行时行为的能力。 重新打开一个类也称为“猴子修补”。 您可以在此处阅读更多相关信息。
At the risk of increasing the level of recursion, I would like to respond although you are referencing my answer at that link.
The misunderstanding is an easy one to make because of our intuitive understanding of reflection as referring to looking inwards. And that's certainly an important aspect of reflection in programming also - in Ruby, for example, we have methods like instance_of to allow objects to ask questions about themselves at runtime.
But take a look at the wikipedia definition of reflection:
As you can see, reflection is more than just runtime self-inspection. It's also the ability to change runtime behavior. Reopening a class is also referred to as "monkey patching". You can read more about it here.