据我了解,CompiledMethod是一个包含方法的编译形式的类。每次编译方法时,都会创建此类的实例。该实例保存在该方法所属的类中。

我的问题是,如果我有一个方法的名称,我如何才能得到一个拥有方法编译形式的实例,以便使用valueWithReceiver:来运行该方法?

是通过使用configureMethodAt:选择器?

最佳答案

我认为我们在这里需要更多的背景信息。

因为使用反射机制,您甚至可以执行以下操作:

CompiledMethod allInstances select: [ :m | m selector = #asString ]

这将为您提供带有选择器asString的所有方法。但是这个动作很奇怪。

您也可以使用#detect:而不是#select:查找单个方法。

如果需要评估所有找到的方法,可以使用:
CompiledMethod allInstances
    select: [ :m | m selector = #asString ]
    thenDo: [ :m | m valueWithReceiver: aReceiver ]

另外,如果您对一种层次结构的方法感兴趣,则可以
YourClass withAllSubclassesDo: [ :class |
    class
        compiledMethodAt: #selector
        ifPresent: [ :method | method valueWithReceiver: aReceiver ]
        ifAbsent:  [ "do nothing" ]

10-05 20:55
查看更多