Runtime introspection, or how to get class members at runtime Fin D

Arafel er.krali at gmail.com
Wed Jun 6 13:28:02 UTC 2018


Hi,

What is the state of runtime introspection in D, specifically for 
classes? Is there any way to get *at runtime* the (public or otherwise 
accessible) members of a class?

I have had a look as TypeInfo_Class [1], but apparently I can only get a 
list of types and offsets... which would be almost good enough, if not 
because the names of the members are missing, or at least I haven't been 
able to find them.

In this case, what I'm trying to do is to serialize / dump / print the 
contents of an object (class instance) without knowing its actual 
runtime type.

Before somebody suggests compile time introspection, the "main" code 
where this routine lives only provides a base class, and it's up to 
dlopen'ed plugins to provide the actual implementation... so I'm sorry 
but no compile-time solution can possibly work.

Also, having each derivative class provide their own dumping information 
is not practical, I'd rather have it automated.

I know it might not be the most idiomatic D, but as somebody with mostly 
a Java background (with some C and just a bit of C++) it seems something 
really straightforward to me: myObject.getClass().getFields() [2].

Also, I know I could add some UDA or even crawl the modules and have 
this information generated automatically at compilation time and added 
to the type itself in a member, and I might even end up doing it, but 
honestly, I think it's something that the language should provide in a 
kind of easy / accessible way.

Powerful as compile-time introspection is, I think runtime shouldn't be 
forgotten either :-)

Thanks,

A.

[1]: https://dlang.org/library/object/type_info__class.html
[2]: 
https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getFields--


More information about the Digitalmars-d-learn mailing list