Reflection is about modifying the code according to the needs arising during the runtime. In the normal scenario, the instructions are executed and the data is processed. Going by the ways of reflection, as the data comes in for processing, the instructions are processed according to the needs based on the data coming in. For an example, consider a group of objects in a single collection object being sent to a method. While extracting the various objects at the destination i.e. the method, the objects being of different types are to be type casted according to the object class types, so at the runtime the object name will give the class name and we can type cast the object accordingly. In reflection, we do not hard code the entire program, but we only say what is to be done when a certain kind of data is received. There are different kinds of reflection, usually the reflection by default refers to the type dynamic reflection which modifies the code duing the runtime. The other kind being of the static reflection that takes place during the compile time vis a’ vis preprocessing of the macros in a C source code.Reflection does not pertain to a programming language per se, but to the categories in which they come in according to the ways of compiling and execution.
Consider an example in Java,
without reflection,
Bank b = new Bank();int a = b.getAC();
Reflection is used,
Class c = Class.forName(args[0]);
Method m[] = c.getDeclaredMethods();
for (int i = 0; i < m.length; i++)
System.out.println(m[i].toString());
One of the disadvantages of using reflection is that the code is not very readily readable and nderstandable. The other problem is the that some errors that we get during compile time in the previous code may not occur here and will only show during the runtime.For example, giving a wrong class name will show up during the compile time in the first scenanrio and will show only in the runtime in the second scenario i.e. with Reflection.This makes it tougher for the programmer to debug.
The conventional execution of a program in C and other procedural languages is preprocessing, compiling, linking and running(i.e. conversion to native machine code for the results). Then there are languages which are interpreted like Lisp and then there are others where first compilation takes place and then interpretation of the bytcode is done like Java. Reflection works by using the structure of the code during the runtime. Languages like C/C++ do not support Reflection as the compiled code does not save the metadata of the structure. The interpreted languages do save the metadata, so also Java supports Reflection.