Pharo中如何获取指定类的所有Setter方法?
Hey there! I remember struggling with this exact question when I was new to Pharo—don't worry, there are a couple of simple, reliable ways to get those setter methods. Let's break them down using your ClassA example:
1. Use the Method Protocol (Most Direct for Your Case)
Since you mentioned your setter methods are already grouped under the setters protocol, this is the easiest approach. Pharo lets you fetch all methods in a specific protocol directly with this code:
ClassA methodsInProtocol: #setters
Running this will return a collection containing exactly your name: and age: methods. This works perfectly because you've already organized your setters into a dedicated protocol—no extra filtering needed!
2. Filter by Setter Naming Pattern (For Unorganized Protocols)
If you ever need to find setters without relying on a protocol, you can use Pharo's method selector rules. Setters in Pharo almost always end with a colon (:) and are instance methods. Here's a quick way to grab them:
ClassA instanceMethods select: [:method | method selector endsWith: ':']
This will get all instance methods with a colon at the end. Note: This might include non-setter methods (like do: or with:) if your class has them, so it's less precise than using the protocol.
Extra Precise: Check if the Method Assigns to an Instance Variable
For absolute accuracy (to only get methods that actually set an instance variable), you can inspect the method's parse tree:
ClassA instanceMethods select: [:method | method parseTree isAssignment and: [ method parseTree variable isInstanceVariable and: [ method selector = (method parseTree variable name , ':') asSymbol ] ] ]
This checks three key things:
- The method contains an assignment operation
- The assignment targets an instance variable of the class
- The method's selector matches the variable name plus a colon (e.g.,
name:for thenamevariable)
This will only return true setter methods, even if you have other colon-ending methods in your class.
For your ClassA example, either the protocol method or the precise parse tree check will give you exactly the name: and age: methods you need.
内容的提问来源于stack exchange,提问作者Mansour Faouziel

