. .


ST 4U 351: Reflecting with instance variable names

March 1, 2013 10:25:31.567

Today's Smalltalk 4 You looks at reflection using instance variable names. If you have trouble viewing it here in the browser, you can also navigate directly to YouTube. To watch now, click on the image below:


If you have trouble viewing that directly, you can click here to download the video directly. If you need the video in a Windows Media format, then download that here.

You can also watch it on YouTube:

Today we'll put a few pieces together on reflection in Smalltalk. Let's assume that you've read some data from an external source into a dictionary, with data like this:

dict := Dictionary new.
dict at: 'id' put: 101.
dict at: 'first' put: 'James'.
dict at: 'last' put: 'Robertson'.

Now, what if you want to create an instance of class Person and fill it with that data - but not using the sort of slot binding approach assumed by #instVarAt:put:? Consider the following:

person := Person new.
dict keysAndValuesDo: [:key :value |
	| msg |
	msg := (key, ':') asSymbol.
	person perform: msg with: value].

Notice how we assume that the dictionary keys are the names of variables, and we construct the messages that get sent to the object. Realistically, you would want exception/error handling around that, for cases where the file format and the class format get out of synch - but that's the basic approach, and it's used commonly in Smalltalk.

Need more help? There's a screencast for other topics like this which you may want to watch. Questions? Try the "Chat with James" Google gadget over in the sidebar.

Tags: , ,

[st4u351-iPhone.m4v ( Size: 931310 )]

posted by James Robertson

 Share Tweet This