[英]Refactoring methods and creating copies with a different name in Pharo Smalltalk?
我正在嘗試重構和一些自定義功能。 有沒有一種方法可以將方法復制到與原始類相同但使用新名稱的類? (本質上是創建一個非常淺的副本)您可以通過編輯方法源來手動完成此操作,但是可以通過編程方式完成嗎?
例如:
doMethodName: anArgument
^ anObject doThat with: anArgument
變為:
doNewMethodName: anArgument
^ anObject doThat with: anArgument
您可以通過向目標類發送compile:
消息來編譯方法。
method := Float>>#cos
或method := Float methodNamed: #cos
檢索源代碼
method sourceCode
將以字符串形式返回方法代碼 method ast
(或method parseTree
)將返回代碼作為已解析的樹表示形式 將代碼編譯成一個類(可選地帶有協議)
TargetClass compile: sourceCode
或 TargetClass compile: sourceCode classified: protocol
所以如果你有
Something>>doMethodName: anArgument
^ anObject doThat with: anArgument
你可以做
code := (Something>>#doMethodName:) sourceCode.
"replace all matches"
newCode := code copyReplaceAll: 'doMethodName:' with: 'doNewMethodName:'.
"or just the first"
newCode := code copyWithRegex: '^doMethodName\:' matchesReplacedWith: 'doNewMethodName:'.
Something compile: newCode.
sourceCode
以字符串sourceCode
返回代碼,這不是最好的操作。 如果只想更改方法名稱,則可以在AST中對其重命名,例如
tree := (Something>>#doMethodName:) parseTree.
tree selector: 'doNewerMethodName:'.
Something compile: tree newSource.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.