Reflection is a mechanism making it possible to investigate yourself.
If we are speaking about programming languages, reflection is used
to investigate format of objects at runtime, invoke methods and access fields
of these objects. Reflection is required if you want to implement some generic code
which can work with objects of unknown (at the time of creation of this code) types.
There are several tasks in which reflection can be used:
remote method invocation, serialization, object dumps, database interfaces.
How it works? Given some object we first should ask for its
As a result we are given class descriptor, which provides information about class methods and
fields. We can use these field descriptors to fetch/store object fields and can use
method descriptors to lookup and invoke methods.
Many programming languages provide built-in reflection mechanism. For example, in Java
there is special package
. But unfortunately C++
doesn't support reflection. Not so long ago first step was made in this direction -
RTTI support was added to the language. But RTTI provides only very restricted subset of reflection:
it allows to get object compile-time and runtime type (it is possible to get object runtime type
only if object class contains virtual functions). You can compare types and you can get type name -
and that is all you can do with RTTI.
There are several ways of extracting type information for C++: