The simplest form of reflection available in D is runtime type information, which is available through the typeid()
operator. It is used extensively by the druntime
implementation and is integral to the safe dynamic casting of classes.
Let's execute the following steps to get dynamic runtime type information:
In most cases, you only need to write
typeid(variable_or_type)
.If you want to get a dynamic class type through an interface, first cast it to
Object
, check fornull
, and then usetypeid(the_casted_object)
.
The code is as follows:
TypeInfo typeInfoAboutInt = typeid(int); typeInfoAboutInt = typeid(1); // also works
The compiler and the runtime library automatically define type information for all types. This information is found in static TypeInfo
objects, which is retrieved by reference using the typeid()
operator. The definition of the TypeInfo
interface is found in the automatically-imported object.d
module of druntime,...