![](/img/trans.png)
[英]squeak(smalltalk) how to get all the methods of an object (inherited methods too)
[英]How to find all methods available in Smalltalk and search by name?
在 Smalltalk 中,有没有办法搜索(任何对象的)所有可用方法,比如包含单词
convert<\/code> (不区分大小写的搜索),还包含单词
string<\/code> ?
(方法名,不是源代码)
"
在Smalltalk中,您可以直接访问所有类,它们的方法和源代码,因此您可以浏览它们。
遍历所有类,然后从每个类中选择符合您需求的所有方法(或使用Finder工具)。
Object withAllSubclasses flatCollect: [ :cls |
cls methods select: [ :method |
(method selector includesSubstring: 'convert' caseSensitive: false) and: [
(method selector includesSubstring: 'string' caseSensitive: false) ]
]
].
GST没有那么好的API,但它也可以做到。
(Object withAllSubclasses collect: [ :cls |
cls methodDictionary ifNotNil: [ :dict |
dict values select: [ :method |
(method selector asLowercase indexOfSubCollection: 'convert' asLowercase) > 0 and: [
(method selector asLowercase indexOfSubCollection: 'string' asLowercase) > 0 ]
]
]
]) join
(也是Pharo和Squeak,还有ifNotNil:
还有GNU Smalltalk)
大众没有#flatten
,所以它是明确实现的。 对于不区分大小写的搜索#findSameAs:startingAt:wildcard:
也可以使用。
(Object withAllSubclasses collect: [ :cls |
cls methodDictionary values select: [ :method |
(method selector asLowercase findString: 'convert' asLowercase startingAt: 1) > 0 and: [
(method selector asLowercase findString: 'string' asLowercase startingAt: 1) > 0 ]
]
]) inject: #() into: [ :arr :each | arr, each ]
海豚似乎有不同的对象模型,请参阅下面的Leandro的答案 。
这可能不适用于所有的smalltalk方言,但它至少适用于吱吱声和pharo(其他小方可能有类似的工具/类)
SystemNavigation default browseAllSelect:[:e |
(e selector includesSubstring:'convert' caseSensitive:false)
and:[e selector includesSubstring:'string' caseSensitive:false]]
这更像是@Peter给出的答案的补充。
请注意,在某些方言(例如,Dolphin)中,消息#withAllSubclasses
将仅收集类,而不是元类。 因此,@ Peter的答案中的枚举应该以明确的方式添加所有元类。
例如,
selectors := OrderedCollection new.
Object withAllSubclasses do: [:class | | matching |
matching := class selectors select: [:s |
(s includesString: 'onvert') and: [s includesString: 'tring']].
selectors addAll: matching.
matching := class class selectors select: [:s |
(s includesString: 'onvert') and: [s includesString: 'tring']].
selectors addAll: matching].
^selectors
请注意,我已经删除了'convert'
和'string'
的第一个字母,以便廉价地防止案例不匹配。
与我的代码的另一个区别是它迭代了类的selectors
而不是它的方法。
UPDATE
请注意,我使用了两个枚举,因为我们不能这样做:
class selectors , class class selectors select: [:s |
原因是一个class
的selectors
进入一个Set
,这些不理解#,
我们本可以做到:
all := class selectors addAll: class class selectors; yourself.
all selectors select: [:s |
等(注意使用#yourself
)
这是为上面的列表添加不同的风味。
Object withAllSubclasses flatCollect: [ :cls | cls methodDictionary values select: [ :method | (method selector includesSubstring: 'convert' caseSensitive: false) and: [ (method selector includesSubstring: 'string' caseSensitive: false) ] ] ].<\/code><\/pre>"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.