Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is Reflection and when is it a good approach?

What exactly is Reflection? I read the Wikipedia article on this subject and I understand that it is a kind of meta-programming, where the program can modify itself at run-time, but what does this mean? In what kind of situations is this a good approach and when is it the best to use it?

like image 881
JPCosta Avatar asked May 14 '09 16:05

JPCosta


People also ask

What is reflection approach?

Reflection is an approach that encourages deep thinking by an individual about their existing knowledge and capabilities, how it has been supported or challenged by new learning and experience, and the identification of strengths to promote and weaknesses/limitations to address.

What makes a reflection good?

The most useful reflection involves the conscious consideration and analysis of beliefs and actions for the purpose of learning. Reflection gives the brain an opportunity to pause amidst the chaos, untangle and sort through observations and experiences, consider multiple possible interpretations, and create meaning.

When should reflection be used?

Reflection allows programmer to access entities in program dynamically. i.e. while coding an application if programmer is unaware about a class or its methods, he can make use of such class dynamically (at run time) by using reflection. It is frequently used in scenarios where a class name changes frequently.

Why is reflection good for learning?

Regular reflection helps students learn, and some simple strategies can make it a regular and meaningful routine. We know that reflection increases student learning. It supports growth mindset and encourages students to improve and learn from their mistakes.


2 Answers

Reflection is a facility where you can query an object about its attributes at runtime. For example, Python, Java and .Net have facilities where you can find the instance variables or methods of an object.

An example of an application for reflection is an O/R mapping layer. Some use reflection to construct an object by quering its properties at runtime and dynamically populating an instance. This allows you to do this programatically based on metadata from some sort of data dictionary without having to recompile the application.

To take a simple example, I'll use Python because its reflection facilities are very simple to use and involve less boilerplate than those of java or .Net.

ActivePython 2.5.2.2 (ActiveState Software Inc.) based on
Python 2.5.2 (r252:60911, Mar 27 2008, 17:57:18) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class foo:
...     def __init__(self):
...             self.x = 1
...
>>> xx = foo()      # Creates an object and runs the constructor
>>> xx.__dict__     # System metadata about the object
{'x': 1}
>>> a = xx.__dict__ # Now we manipulate the object through 
>>> a['y'] = 2      # its metadata ...
>>> print xx.y      # ... and suddenly it has a new instance variable
2                   
>>>

Now, we've used basic reflection to examine the instance variables of an arbitrary object. The special variable __dict__ on Python is a system property of an object that has a hash table of its members keyed by the variable (or method) name. We have reflectively examined the object and used the reflection facilities to artificially poke a second instance variable into it, which we can then display by invoking it as an instance variable.

Note that this particular trick doesn't work on Java or .Net, as the instance variables are fixed. The type system of these languages doesn't allow new instance variables to be added at runtime in the way that python's 'duck' typing system does. However, you could have reflectively updated the value of an instance variable that was declared in the type definition.

You can also use reflection to dynamically construct method invocations and perform various other neat tricks such as instantiating an object based on a parameter. For example, if you had some sort of plugin based system where certain capabilities were optional, you could use reflection to query the plugin about what services it offered (perhaps by querying whether certain interfaces were implemented) without requiring explicit metadata.

Many dynamic language interfaces such as OLE automation use reflection as an integral part of the interface.

like image 190
ConcernedOfTunbridgeWells Avatar answered Oct 21 '22 06:10

ConcernedOfTunbridgeWells


It's not so much modifying code at execution time, but examining objects and asking them to execute code without knowing their type statically.

One simple way of describing it would be "a somewhat painful way of making a statically typed language behave dynamically."

EDIT: Uses:

  • Configuration (e.g. take an XML file which specifies types and properties, then construct appropriate objects)
  • Testing (unit tests which are identified by name or attributes)
  • Web services (in .NET at least, a lot of reflection is used in the core web service engine)
  • Automatic event wiring - provide a method with an appropriate name, e.g. SubmitButton_Click and ASP.NET will attach that method as a handler for the SubmitButton's Click event (if you have autowiring turned on)

Is it a good idea? Well, only when the alternatives are painful. I prefer static typing when it doesn't get in the way - then you get lots of compile-time goodness, and it's faster too. But when you do need it, reflection lets you do various things which otherwise just wouldn't be possible.

like image 21
Jon Skeet Avatar answered Oct 21 '22 06:10

Jon Skeet