获取CompiledMethod类的实例

时间:2014-12-11 17:07:09

标签: smalltalk squeak

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

我的问题是,如果我有一个方法的名称,我怎样才能获得保存方法的编译形式的实例,以便使用valueWithReceiver运行该方法?

是使用compiledMethodAt:selector吗?

3 个答案:

答案 0 :(得分:3)

我认为我们需要更多背景。

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

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" ]

答案 1 :(得分:2)

如果你不确定,你收到的消息是什么,你可以随时询问结果课程。打印:

(Behavior compiledMethodAt: #compiledMethodAt:) class

在这种情况下,它是CompiledMethod - 确切地说,你在寻找什么。 是的,您可以使用valueWithReceiver:编译的方法。

答案 2 :(得分:0)

您可以让虚拟机为您查找方法,并使用如下表达式运行它:

object perform: selector

虚拟机将在对象的类中查找与选择器关联的方法,并以对象作为接收器运行它。此消息有类似形式的传递参数。

相关问题