Calling method by name.

spir denis.spir at gmail.com
Fri Feb 4 11:03:32 PST 2011


On 02/04/2011 04:33 PM, Jacob Carlborg wrote:
> On 2011-02-04 04:29, Robert Jacques wrote:
>> On Thu, 03 Feb 2011 08:49:54 -0500, Jacob Carlborg <doob at me.com> wrote:
>>

>> Well, opDispatch does exactly that. __reflect, on the other hand, was
>> designed as a quasi-backend function primarily for a) internal use
>> (hence the double underscore), b) scripting language
>> interfacing/implementing and c) user-extension. So efficiency was of key
>> importance. And the reflection system is extensible, as Variant knows to
>> call __reflect on user defined types. This makes things like prototype
>> style objects possible. (There's even a beta implementation of a
>> prototype object in the library) But this requires that the use
>> __reflect methods not be templated.
>>
>> I'm not well versed in dynamic reflection and its use cases, so when I
>> considered the combination of a runtime method name and compile-time
>> argument type information, I classed it as 'rare in practice'. But if
>> that's not the case, I'd like to know and would greatly appreciate a use
>> case/unit test.
>
> I recommend looking at Ruby, it has very good support for runtime reflection.
> ActiveRecord in Rails is hevaly based on runtime reflection. For example, given
> the following Ruby class:
>
> class Post < ActiveRecord::Base
> end
>
> The class "Post" maps to the database table "posts", no configuration is
> necessary. Then you can use the column names in the table as fields to set and
> get data, like this:
>
> post = Post.new
> post.title = "some title"
> post.body = "the body"
> post.save # will update the database
>
> All this is done using runtime reflection. Then you can query the database,
> also using runtime reflection:
>
> Post.find_by_name_and_body("some title", "the body")
>
> Will find the first row where "title" and "body" matches the given values.

FWIW, python example of "Calling method by name" (using no exotic feature):

class C:
     def __init__(self, x):
         self.x = x
     def write (self, thing):
         print "%s == %s ? %s" \
               %(self.x,thing, self.x==thing)

def runMethodWithArgs (object, name, *args):
     method = getattr(object, name)
     method(*args)

c= C(1.11)
runMethodWithArgs(c, "write", 2.22)
# --> 1.11 == 2.22 ? False

(Explanations if needed.)

Denis
-- 
_________________
vita es estrany
spir.wikidot.com



More information about the Digitalmars-d mailing list