Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 38 ยท Reflection and Metaclasses

Reflection and Introspection

Learn how Smalltalk objects inspect themselves at run time: class, respondsTo:, selectors, instance variables and perform:. Real code is read-only; runnable JavaScript stand-ins show each idea.

In most languages the program is one thing and the tools that examine it are another. In Smalltalk they are the same thing. Classes, methods, even the compiler are ordinary objects that you can ask questions. This ability to look at your own program while it runs is called reflection, and it is the reason Smalltalk tools such as the inspector and the debugger are so powerful.

This lesson covers the everyday reflective messages: asking an object for its class, asking whether it understands a message, listing its methods and variables, and sending a message whose name is only known at run time. Smalltalk itself does not run on this site, so the real code is shown read-only. Each idea also has a small JavaScript stand-in that you can run and change. The stand-ins mimic the idea, not the exact Pharo or Squeak API.

Asking an object about itself

Every object can answer questions about its own nature. These messages work in Pharo, Squeak and most other dialects (read-only):

SMALLTALK
3 class.                         "SmallInteger"
3 class class.                   "SmallInteger class"
'hello' isString.                "true"
3 isKindOf: Integer.             "true"
3 isMemberOf: Integer.           "false: its class is SmallInteger"
3 respondsTo: #factorial.        "true"
3 respondsTo: #fly.              "false"

isKindOf: accepts the class itself or any subclass. isMemberOf: is stricter and only accepts the exact class. Beginners tend to overuse both. A good Smalltalker prefers respondsTo: or, better, just sends the message and lets polymorphism do the work. Asking "what are you?" is usually a sign that behaviour should have been a method on the object instead.

Listing methods and variables

Classes keep dictionaries of their methods and the names of their variables. You can read them directly (read-only):

SMALLTALK
Point selectors.                 "the messages Point itself defines"
Point allSelectors size.         "including every inherited message"
Point instVarNames.              "#(#x #y)"
Point superclass.                "Object"
Point subclasses.                "classes that inherit from Point"
(Point >> #dist:) sourceCode.    "the source text of one method"

selectors lists only what a class defines itself, while allSelectors includes everything it inherits. Point >> #dist: fetches a compiled method, which is an object too and can tell you its source, its class, its arguments and the messages it sends.

Here is a runnable stand-in. A JavaScript class plays the part of a Smalltalk class, and a few helper functions answer the same questions.

JS Stand-in: asking a JavaScript object about itself

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Object.keys(rex) plays the role of instVarNames: it lists the state stored in this one object. Change the class and add a method to see both lists grow.

Reading and writing variables by name

Smalltalk lets you reach instance variables by name without an accessor, using instVarNamed: and instVarNamed:put:. The inspector uses exactly these messages (read-only):

SMALLTALK
| p |
p := 3 @ 4.
p instVarNamed: 'x'.             "3"
p instVarNamed: 'y' put: 10.
p.                               "3@10"
p instVarAt: 1.                  "3, by position"

This breaks encapsulation on purpose. It is meant for tools, serializers and debuggers, not for application logic. If you find yourself writing instVarNamed: in business code, add a proper accessor instead.

Sending a message by name: perform:

perform: sends a message whose name is held in a variable. It is Smalltalk's answer to a switch statement full of method names (read-only):

SMALLTALK
3 perform: #factorial.                    "6"
3 perform: #+ with: 4.                    "7"
'hello' perform: #copyFrom:to: with: 2 with: 4.   "'ell'"

Because a selector is just a symbol, you can read it from a file, a menu item or a network request and run it. This is the heart of many plugin systems and command dispatchers. It also means you should validate the symbol first with respondsTo:.

JS Stand-in: perform with a guard

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last command fails with a message that mirrors Smalltalk's famous "does not understand" error. The next lessons build on this: metaclasses and doesNotUnderstand: proxies.

A picture of the idea

flowchart LR
  O["an object"] -->|"class"| C["its class"]
  C -->|"selectors / instVarNames"| M["method dictionary<br/>and variable names"]
  C -->|"superclass"| S["parent class"]
  O -->|"perform: #sel"| R["run the method found by lookup"]

Reflection turns the object, its class and its methods into things you can query and call.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which message asks whether an object can handle a selector?

    respondsTo: checks the full lookup chain for the selector. isKindOf: only checks the class hierarchy.
  2. 2. What is the difference between selectors and allSelectors?

    selectors lists what the class defines itself; allSelectors walks up the superclass chain as well.
  3. 3. What does 3 perform: #+ with: 4 return?

    • is an ordinary binary selector, so perform:with: sends 3 + 4.
  4. 4. When is instVarNamed: appropriate?

    It bypasses encapsulation, so keep it for tools that must look inside any object.

Summary

  • Smalltalk objects, classes and methods are all inspectable at run time.
  • class, isKindOf:, respondsTo:, selectors, allSelectors and instVarNames answer questions about structure.
  • instVarNamed: and instVarNamed:put: read and write variables by name; use them in tools only.
  • perform: sends a message chosen at run time, so guard it with respondsTo:.
  • The JavaScript examples are stand-ins that imitate the ideas; the Smalltalk blocks are read-only.

Next: Classes Are Objects and Metaclasses