Calling method by name.

Jacob Carlborg doob at me.com
Thu Feb 3 05:49:54 PST 2011


On 2011-02-03 05:52, Robert Jacques wrote:
> On Wed, 02 Feb 2011 12:55:37 -0500, %u <fghf at jhgjhb.com> wrote:
>
>> I know is possible to create an object from its name. It's possible to
>> call a method from that object if the name is only known at runtime?
>>
>> Would something like the following be possible?
>>
>> string classname, methodname;
>> // Ask the user for class and method.
>> auto obj = Object.factory(classname);
>> invoke(methodname, obj, param1, param2);
>>
>> Thanks
>
> I've been working on an update to std.variant, which includes a
> compile-time reflection to runtime-reflection system. (See
> https://jshare.johnshopkins.edu/rjacque2/public_html/) From the docs:
>
> Manually registers a class with Variant's runtime-reflection system.
> Note that Variant automatically registers any types it is exposed. Note
> how in the example below, only Student is manually registered; Grade is
> automatically registered by Variant via compile-time reflection of Student.
>
> 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);
> }
>
> And dynamic method/field calls are handled via the __reflect(string
> name, Variant[] args...) method like so:
>
> grade.__reflect("mark",Variant(96.6));
> assert(grade.__reflect("mark") == 96.6);

Why would you need to pass in Variants in __reflect? Why not just make 
it a variadic method and automatically convert to Variant?

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list