Reflection is generally defined as a program’s ability to inspect itself and modify its logic at execution time. In less technical terms, reflection is asking an object to tell you about its properties and methods, and altering those members (even private ones). In this lesson, we’ll dig into how this is accomplished, and when it might prove useful.
A Little History
At the dawn of the age of programming, there was the assembly language. A program written in assembly resides on physical registers inside the computer. Its composition, methods and values could be inspected at any time by reading the registers. Even more, you could alter the program while it was running by simply modifying those registers. It required some intimate knowledge about the running program, but it was inherently reflective.
As higher-level programming languages (like C) came along, this reflectivity faded and disappeared. It was later re-introduced with object-oriented programming.
Today, most programming languages can use reflection. Statically typed languages, such as Java, have little to no problems with reflection. What I find interesting, however, is that any dynamically-typed language (like PHP or Ruby) is heavily based on reflection. Without the concept of reflection, duck-typing would most likely be impossible to implement. When you send one object to another (a parameter, for example), the receiving object has no way of knowing the structure and type of that object. All it can do is use reflection to identify the methods that can and cannot be called on the received object.
Comments
Be the first to write a comment
You must me logged in to write a comment.