[squeak-dev] Interception messages in Squeak

David T. Lewis lewis at mail.msen.com
Mon Apr 15 04:59:05 UTC 2013


On Mon, Apr 15, 2013 at 01:17:40PM +0900, Yann-Ga?l Gu?h?neuc wrote:
> 
> 	Dear all,
> 
> I am trying to understand better reflection in Smalltalk. I am using 
> the latest version of Squeak (v4.3). I want to intercept every 
> message sent to instances of one of my classes. I assumed that I 
> could override the method `ProtoObject>>withArgs:executeMethod` but 
> St?phane (Ducasse) explained me that for performance reason, this 
> method is not used (this is my own summary of his answer). Which 
> method should I override / how could intercept sent messages?
> 
> Here is the code of my attempt:
> 
>     Object subclass: #C
>     	instanceVariableNames: 'i'
>     	classVariableNames: ''
>     	poolDictionaries: ''
>     	category: 'CSE3009'.
> 
>     C class compile: 'newWithi: anInt
>     	^(self new) i: anInt ; yourself.'.
> 
>     C compile: 'withArgs: someArgs executeMethod: aMethod
>     	Transcript show: ''Caught: ''.
>     	^ super withArgs: someArgs executeMethod aMethod.'.
> 
>     C compile: 'foo: aText
>     	Transcript show: aText.
>     	Transcript show: i.
>     	Transcript cr.'.
> 
>     C compile: 'i: anInt
>     	i := anInt.'.
> 
>     o := C newWithi: 42.
>     o foo: 'This is foo: '.
> 
> Executing this entire piece of code yields:
> 
>     This is foo: 42
> 
> When I would like to have:
> 
>     Caught: This is foo: 42
> 
> 	I was told about wrapper objects and MethodWrapper (see 
> http://stackoverflow.com/questions/15975340/interception-messages-in-squeak) 
> but in my quest to understand reflection, I would like to know if there 
> would be something more "reflective", typically overriding a message :-)
> 
> 	Thank you very much in advance!
> 	Yann

Try this after compiling your code:

  "Ask the class for the compiled method that you want to execute"
  theCompiledMethod := C compiledMethodAt: #foo: .
  
  "Make an array of size one containing the argument, a string"
  theArguments := { 'This is foo: ' } .
  
  "Execute the compiled method as if it was a message send to the object"
  o withArgs: theArguments executeMethod: theCompiledMethod.
  
  ==> Caught: This is foo: 42

Dave



More information about the Squeak-dev mailing list