Run-time reflection for class inheritance
Michael Green
abc.mikey at gmail.com
Sun Dec 1 12:26:03 UTC 2019
I don't know if this would be a sensible approach to try and get
at the actual class types for objects stored in some container at
runtime?
I have noticed that this approach doesn't work if Event is an
interface rather than a ancestor class.
```
import std.stdio;
import std.string;
import std.traits;
import std.conv;
interface Event {
void report() {
writeln("an event");
}
}
class EventTimer : Event {
override void report() {
writeln("timer event");
}
}
class EventSocket: Event {
override void report() {
writeln("socket event");
}
}
void main(string[] args) {
Event[] events;
foreach (arg; args[1..$]) {
// just something to pick actual type at runtime
if (to!int(arg) > 5) {
events ~= new EventTimer();
} else {
events ~= new EventSocket();
}
}
foreach (event; events) {
switch (event.classinfo.name) {
case fullyQualifiedName!EventTimer:
writeln("found timer event");
break;
case fullyQualifiedName!EventSocket:
writeln("found socket event");
break;
default:
throw new Exception("unknown event type");
break;
}
event.report();
}
}
```
More information about the Digitalmars-d-learn
mailing list