Chances of D getting proper runtime reflection?

Robert Jacques sandford at jhu.edu
Sun Aug 21 17:43:25 PDT 2011


On Sun, 21 Aug 2011 11:20:14 -0400, Jacob Carlborg <doob at me.com> wrote:
> On 2011-08-21 15:20, Robert Jacques wrote:
>> On Sun, 21 Aug 2011 06:55:52 -0400, Jacob Carlborg <doob at me.com> wrote:
>>
>>> What are the chances of D getting proper runtime reflection? Something
>>> like this:
>>>
>>> class Foo
>>> {
>>> private int a;
>>>
>>> private void bar (int i)
>>> {
>>> a = i;
>>> }
>>> }
>>>
>>> auto foo = new Foo;
>>> Object o = foo;
>>> o.setInstanceVariable("a", 3);
>>> assert(foo.a == 3);
>>>
>>> This would be useful as well:
>>>
>>> o.send("bar", 5);
>>> assert(foo.a == 5);
>>> assert(foo.a == o.getInstanceVariable("a"));
>>>
>>> Currently I have most use of the first example. These example should
>>> work regardless if the fields/methods are private, protected or public.
>>>
>>> As far as I know this wouldn't require any changes to the language, only
>>> the compiler and runtime would need to be modified. To me, it doesn't
>>> look that complicated to implement, the runtime just needs to store an
>>> associative arrays that maps names of instance variables and methods to
>>> their addresses. This could probably be stored in the ClassInfo.
>>> Something like this:
>>>
>>> Foo.classinfo.setInstanceVariable(foo, "a", 3);
>>>
>>> And this could be shorted to:
>>>
>>> o.setInstanceVariable("a", 3);
>>>
>>> "setInstanceVariable" could just forward the call to the class info.
>>>
>>
>> I've basically done this entirely in library code: see
>> https://jshare.johnshopkins.edu/rjacque2/public_html/variant.mht
>
> The whole point was to have direct support in the language/runtime so
> these library solution were not needed. Does your solution work when the
> static type is Object and the runtime type is a subclass?
>

Yes, so long as at some point the subclass is registered by variant, either manually or auto-magically via reflection on another type. The docs had an example of this:

         module example;
         class Grade   { real  mark;  }
         class Student { Grade grade; }
         void main(string[] args) {
             Variant.__register!Student;
             Variant grade = Object.factory("example.Grade");
             grade.mark(96.6);
             assert(grade.mark == 96.6);
         }

notice how Student had to be manually registered, but Grade was registered auto-magically.


More information about the Digitalmars-d mailing list