10. Reflection. Birds-eye view © Oscar Nierstrasz ST — Reflection 1.2 Reflection allows you to both examine and alter the meta-objects of a system. Using.

Slides:



Advertisements
Similar presentations
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Advertisements

Dynamic Object-Oriented Programming with Smalltalk 1. Introduction Prof. O. Nierstrasz.
Dynamic Object-Oriented Programming with Smalltalk 1. Introduction Prof. O. Nierstrasz.
7. Optimization Prof. O. Nierstrasz Lecture notes by Marcus Denker.
From Objects to Actors Study of a Limited Symbiosis in Smalltalk-80.
Introduction to Software Engineering 7. Modeling Behaviour.
S.Ducasse 1 Metaclasses in 7 Steps Classes are objects too... Classes are instances of other classes... One model applied twice.
11. A bit of Smalltalk. © O. Nierstrasz P2 — A bit of Smalltalk 11.2 A bit of Smalltalk Overview  Some history  Smalltalk syntax & object model  The.
2. Smalltalk Basics. © Oscar Nierstrasz ST — Smalltalk Basics 2.2 Roadmap  Everything is an Object  Syntax on a Postcard  Three Kinds of Messages 
12. Summary, Trends, Research. © O. Nierstrasz PS — Summary, Trends, Research Roadmap  Summary: —Trends in programming paradigms  Research:...
Stéphane Ducasse«ChapterNr».1 Arthur Riel Design Heuristics from Object-Oriented Design Heuristics by Arthur Riel Read the Heuristics… –Find reasons why.
7. Understanding Classes and Metaclasses. © Oscar Nierstrasz ST — Understanding Classes and Metaclasses 7.2 Roadmap  Metaclasses in 7 points  Indexed.
ESE Einführung in Software Engineering N. XXX Prof. O. Nierstrasz Fall Semester 2009.
Stéphane Ducasse9.1 Inheritance Semantics and Lookup.
© Oscar Nierstrasz ST — Smalltalk Basics 2.1 Change sets  Make sure your changes are logged to a new change set.
6. Debugging. Birds-eye view © Oscar Nierstrasz ST — Introduction 1.2 It can be easier to talk to objects than to read classes — The system is alive.
ESE Einführung in Software Engineering X. CHAPTER Prof. O. Nierstrasz Wintersemester 2005 / 2006.
Stéphane Ducasse 1 The Taste of Smalltalk.
13. A bit of Smalltalk. © Oscar Nierstrasz 2 Roadmap  The origins of Smalltalk  What is Smalltalk?  Syntax in a nutshell  Seaside — web development.
Dynamic Object-Oriented Programming with Smalltalk 1. Introduction Prof. O. Nierstrasz Summer Semester 2006.
13. Traits. Selected literature  Cook. Interfaces and Specifications for the Smalltalk-80 Collection Classes. OOPSLA 1992  Taivalsaari. On the Notion.
Metamodeling Seminar X. CHAPTER Prof. O. Nierstrasz Spring Semester 2008.
2. Smalltalk Basics. © Oscar Nierstrasz ST — Smalltalk Basics 2.2 Roadmap  Everything is an Object  Syntax on a Postcard  Three Kinds of Messages 
Some Basic Points on Classes
© Oscar Nierstrasz ST — Smalltalk Basics 2.1 Change sets  Make sure your changes are logged to a new change set.
ESE Einführung in Software Engineering X. CHAPTER Prof. O. Nierstrasz Wintersemester 2005 / 2006.
6. Debugging. © Oscar Nierstrasz ST — Debugging 6.2 Roadmap  Common syntactic errors  Common semantic errors  Encapsulation errors  Class/instance.
N. XXX Prof. O. Nierstrasz Thanks to Jens Palsberg and Tony Hosking for their kind permission to reuse and adapt the CS132 and CS502 lecture notes.
10. Reflection. © Oscar Nierstrasz ST — Reflection 10.2 Roadmap  What is reflection?  Object meta-operations  Class meta-operations  Method meta-operations.
9. Understanding Classes and Metaclasses. Birds-eye view © Oscar Nierstrasz ST — Introduction 1.2 Reify your metamodel — A fully reflective system models.
7. Fixed Points. © O. Nierstrasz PS — Fixed Points 7.2 Roadmap  Representing Numbers  Recursion and the Fixed-Point Combinator  The typed lambda calculus.
Metamodeling and Metaprogramming Seminar 1. Introduction Prof. O. Nierstrasz Spring Semester 2008.
6. Debugging. © Oscar Nierstrasz ST — Debugging 6.2 Roadmap  Common syntactic errors  Common semantic errors  Encapsulation errors  Class/instance.
10. Reflection. © Oscar Nierstrasz ST — Reflection 10.2 Roadmap  What is reflection?  Object meta-operations  Class meta-operations  Method meta-operations.
03G-1 Everything is an Object Examining builtin classes All these are classes in Little Smalltalk:  Object  Class  Method  Block  Boolean True False.
Stéphane Ducasse«ChapterNr».1 Advanced Classes Indexed Classes Classes as Objects Class Instance Variables and Methods Class Variables Pool Dictionaries.
OORPT Object-Oriented Reengineering Patterns and Techniques X. CHAPTER Prof. O. Nierstrasz.
CP — Concurrent Programming X. CHAPTER Prof. O. Nierstrasz Wintersemester 2005 / 2006.
3. Standard Classes. © Oscar Nierstrasz ST — Standard Classes 3.2 Roadmap  Object  Numbers, Characters, Strings and Arrays  Variables  Blocks and.
3. Standard Classes. Birds-eye view © Oscar Nierstrasz ST — Introduction 1.2 Reify everything — by reifying its entire implementation model, Smalltalk.
Stéphane Ducasse5.1 Smalltalk in a Nutshell OO Model in a Nutshell Syntax in a Nutshell.
12. A bit of Smalltalk. © O. Nierstrasz P2 — A bit of Smalltalk 11.2 Roadmap  Some history  Smalltalk syntax & object model  The Smalltalk environment.
4. Smalltalk Coding Idioms. © Oscar Nierstrasz ST — Smalltalk Coding Idioms 4.2 Roadmap  Snakes and Ladders — Cascade and Yourself  Lots of Little Methods.
12. eToys. © O. Nierstrasz PS — eToys 12.2 Denotational Semantics Overview:  … References:  …
Stéphane Ducasse 1 Smalltalk in a Nutshell.
S.Ducasse Stéphane Ducasse 1 The Taste of Smalltalk.
Subclasses and Subtypes CMPS Subclasses and Subtypes A class is a subclass if it has been built using inheritance. ▫ It says nothing about the meaning.
CS 598 Scripting Languages Design and Implementation 7. Smalltalk 80.
S.Ducasse Stéphane Ducasse 1 Classes and Metaclasses - an Analysis.
CSE 425: Object-Oriented Programming I Object-Oriented Programming A design method as well as a programming paradigm –For example, CRC cards, noun-verb.
S.Ducasse Stéphane Ducasse 1 Design Heuristics.
Objects & Dynamic Dispatch CSE 413 Autumn Plan We’ve learned a great deal about functional and object-oriented programming Now,  Look at semantics.
S.Ducasse Stéphane Ducasse savoie.fr e/ e/ 1 Inheritance Semantics and Method Lookup.
Smalltalk in a.NET World How to write a Smalltalk compiler without writing a VM John Brant
Stéphane Ducasse 1 Singleton.
S.Ducasse 1 7. Understanding Metaclasses. S.Ducasse 2 Roadmap Metaclasses in 7 points Indexed Classes Class Instance Variables Class Variables Pool Dictionaries.
Stéphane Ducasse 1 Some Advanced Points on Classes.
CSCE 314 Programming Languages Reflection Dr. Hyunyoung Lee 1.
S.Ducasse Marcus Denker 1 Working with Bytecodes: IRBuilder and InstructionStream.
S.Ducasse Stéphane Ducasse 1 Smalltalk in a Nutshell.
S.Ducasse Stéphane Ducasse savoie.fr e/ e/ 1 Smalltalk in a Nutshell.
S.Ducasse Stéphane Ducasse 1 Some Advanced Points on Classes.
ISBN Chapter 12 Support for Object-Oriented Programming.
Administrative Issues Lecture 22 – Prolog (III), Fall 2007 CSE3302 Programming Languages, UT-Arlington ©Chengkai Li, HW3 (due at March 18 th ) Essay.
Patterns Protect from Change Rule: if something is going to change, make it an object. Strategy: make algorithm an object so it can change State: make.
1 Case Study: Meta Classes  Class representation in memory  Class variables and class methods  Meta Classes  3 Level System  4 Level System  5 Level.
Smalltalk Meta-Programming Programming Languages HUJI 2010 Yardena Meymann.
S.Ducasse 1 Instance Initialization How to ensure that an instance is well initialized? Automatic initialize Lazy initialization Proposing the right interface.
Methodology Overview 2 basics in user studies Lecture /slide deck produced by Saul Greenberg, University of Calgary, Canada Notice: some material in this.
Reflective Programming in Smalltalk eXterme Metaprogramming
Presentation transcript:

10. Reflection

Birds-eye view © Oscar Nierstrasz ST — Reflection 1.2 Reflection allows you to both examine and alter the meta-objects of a system. Using reflection to modify a running system requires some care.

© Oscar Nierstrasz ST — Reflection 10.3 Roadmap  Reification and reflection  Introspection —Inspecting objects —Querying code —Accessing run-time contexts  Intercession —Overriding doesNotUnderstand: —Anonymous classes —Method wrappers Selected material by Marcus Denker and Stéphane Ducasse

© Oscar Nierstrasz ST — Reflection 10.4 Roadmap  Reification and reflection  Introspection —Inspecting objects —Querying code —Accessing run-time contexts  Intercession —Overriding doesNotUnderstand: —Anonymous classes —Method wrappers Selected material by Marcus Denker and Stéphane Ducasse

Why we need reflection © Oscar Nierstrasz ST — Reflection 10.5 As a programming language becomes higher and higher level, its implementation in terms of underlying machine involves more and more tradeoffs, on the part of the implementor, about what cases to optimize at the expense of what other cases. … the ability to cleanly integrate something outside of the language’s scope becomes more and more limited Kiczales, in Paepcke 1993

© Oscar Nierstrasz ST — Reflection 10.6 What is are Reflection and Reification?  Reflection is the ability of a program to manipulate as data something representing the state of the program during its own execution. —Introspection is the ability for a program to observe and therefore reason about its own state. —Intercession is the ability for a program to modify its own execution state or alter its own interpretation or meaning.  Reification is the mechanism for encoding execution state as data —Bobrow, Gabriel & White, 1993

Reflection and Reification © Oscar Nierstrasz ST — Reflection 7

© Oscar Nierstrasz ST — Reflection 10.8 Consequences  “A system having itself as application domain and that is causally connected with this domain can be qualified as a reflective system” —Maes, OOPSLA 1987 —A reflective system has an internal representation of itself. —A reflective system is able to act on itself with the ensurance that its representation will be causally connected (up to date). —A reflective system has some static capacity of self- representation and dynamic self-modification in constant synchronization

© Oscar Nierstrasz ST — Reflection 10.9 Metaprogramming in Programming Languages  The meta-language and the language can be different: —Scheme and an OO language  The meta-language and the language can be same: —Smalltalk, CLOS —In such a case this is a metacircular architecture

© Oscar Nierstrasz ST — Reflection Structural and behavioral reflection  Structural reflection is concerned with the ability of the language to provide a complete reification of both —the program currently executed —as well as its abstract data types.  Behavioral reflection is concerned with the ability of the language to provide a complete reification of —its own semantics and implementation (processor) —as well as the data and implementation of the run-time system. Malenfant et al., A Tutorial on Behavioral Reflection and its Implementation, 1996

© Oscar Nierstrasz ST — Reflection Roadmap  Reification and reflection  Introspection —Inspecting objects —Querying code —Accessing run-time contexts  Intercession —Overriding doesNotUnderstand: —Anonymous classes —Method wrappers Selected material by Marcus Denker and Stéphane Ducasse

© Oscar Nierstrasz ST — Reflection The Essence of a Class 1. A format —I.e., a number of instance variables and types 2. A superclass 3. A method dictionary

© Oscar Nierstrasz ST — Reflection Behavior class>> new  In Pharo: Behavior class>>new | classInstance | classInstance := self basicNew. classInstance methodDictionary: classInstance emptyMethodDictionary. classInstance superclass: Object. classInstance setFormat: Object format. ^ classInstance NB: not to be confused with Behavior>>new!

© Oscar Nierstrasz ST — Reflection The Essence of an Object 1. Class pointer 2. Values  Can be special: —SmallInteger —Indexed rather than pointer values —Compact classes (CompiledMethod, Array …)

© Oscar Nierstrasz ST — Reflection Metaobjects vs metaclasses  Need distinction between metaclass and metaobject! —A metaclass is a class whose instances are classes —A metaobject is an object that describes or manipulates other objects – Different metaobjects can control different aspects of objects

© Oscar Nierstrasz ST — Reflection Some MetaObjects  Structure: —Behavior, ClassDescription, Class, Metaclass, ClassBuilder  Semantics: —Compiler, Decompiler, IRBuilder  Behavior: —CompiledMethod, BlockContext, Message, Exception  ControlState: —BlockContext, Process, ProcessorScheduler  Resources: —WeakArray  Naming: —SystemDictionary  Libraries: —MethodDictionary, ClassOrganizer

Meta-Operations © Oscar Nierstrasz ST — Reflection “Meta-operations are operations that provide information about an object as opposed to information directly contained by the object...They permit things to be done that are not normally possible” Inside Smalltalk

© Oscar Nierstrasz ST — Reflection pt := pt instVarNamed: 'x'. pt instVarNamed: 'x' put: 33. pt 10 Accessing state  Object>>instVarNamed: aString  Object>>instVarNamed: aString put: anObject  Object>>instVarAt: aNumber  Object>>instVarAt: aNumber put: anObject

© Oscar Nierstrasz ST — Reflection 'hello' class class Smalltalk class Class class Class class class Class class class class 'hello' identityHash Object identityHash 5 identityHash ByteString Point SystemDictionary Class class Metaclass Metaclass class Accessing meta-information  Object>>class  Object>>identityHash

© Oscar Nierstrasz ST — Reflection Changes  Object>>primitiveChangeClassTo: anObject —both classes should have the same format, i.e., the same physical structure of their instances – “Not for casual use”  Object>>become: anotherObject —Swap the object pointers of the receiver and the argument. —All variables in the entire system that used to point to the receiver now point to the argument, and vice-versa. —Fails if either object is a SmallInteger  Object>>becomeForward: anotherObject —Like become: but only in one direction.

© Oscar Nierstrasz ST — Reflection Implementing Instance Specific Methods ReflectionTest>>testPrimitiveChangeClassTo | behavior browser | behavior := Behavior new. “an anonymous class” behavior superclass: Browser. behavior setFormat: Browser format. browser := Browser new. browser primitiveChangeClassTo: behavior new. behavior compile: 'thisIsATest ^ 2'. self assert: browser thisIsATest = 2. self should: [Browser new thisIsATest] raise: MessageNotUnderstood.

© Oscar Nierstrasz ST — Reflection become:  Swap all the pointers from one object to the other and back (symmetric) ReflectionTest>>testBecome | pt1 pt2 pt3 | pt1 := pt2 := pt1. pt3 := pt1 become: pt3. self assert: pt1 = self assert: pt1 == pt2. self assert: pt3 =

© Oscar Nierstrasz ST — Reflection becomeForward:  Swap all the pointers from one object to the other (asymmetric) ReflectionTest>>testBecomeForward | pt1 pt2 pt3 | pt1 := pt2 := pt1. pt3 := pt1 becomeForward: pt3. self assert: pt1 = self assert: pt1 == pt2. self assert: pt2 == pt3.

© Oscar Nierstrasz ST — Reflection Roadmap  Reification and reflection  Introspection —Inspecting objects —Querying code —Accessing run-time contexts  Intercession —Overriding doesNotUnderstand: —Anonymous classes —Method wrappers Selected material by Marcus Denker and Stéphane Ducasse

Code metrics © Oscar Nierstrasz ST — Reflection 25 Collection allSuperclasses size. Collection allSelectors size. Collection allInstVarNames size. Collection selectors size. Collection instVarNames size. Collection subclasses size. Collection allSubclasses size. Collection linesOfCode. Collection allSuperclasses size. Collection allSelectors size. Collection allInstVarNames size. Collection selectors size. Collection instVarNames size. Collection subclasses size. Collection allSubclasses size. Collection linesOfCode

SystemNavigation © Oscar Nierstrasz ST — Reflection 26 SystemNavigation default browseAllImplementorsOf: #,

© Oscar Nierstrasz ST — Reflection Recap: Classes are objects too  Object —Root of inheritance —Default Behavior —Minimal Behavior  Behavior —Essence of a class —Anonymous class —Format, methodDict, superclass  ClassDescription —Human representation and organization  Metaclass —Sole instance

© Oscar Nierstrasz ST — Reflection Classes are Holders of CompiledMethods

© Oscar Nierstrasz ST — Reflection Invoking a message by its name  Asks an object to execute a message —Normal method lookup is performed Object>>perform: aSymbol Object>>perform: aSymbol with: arg 5 factorial 5 perform: #factorial 120

© Oscar Nierstrasz ST — Reflection Executing a compiled method  No lookup is performed! CompiledMethod>>valueWithReceiver:arguments: (SmallInteger>>#factorial) valueWithReceiver: 5 arguments: #() (Integer>>#factorial) valueWithReceiver: 5 arguments: #() Error: key not found 120

MethodReference © Oscar Nierstrasz ST — Reflection 31

Finding super-sends within a hierarchy © Oscar Nierstrasz ST — Reflection 32 class := Collection. SystemNavigation default browseMessageList: (class withAllSubclasses gather: [:each | each methodDict associations select: [:assoc | assoc value sendsToSuper] thenCollect: [:assoc | MethodReference class: each selector: assoc key]]) name: 'Supersends of ', class name, ' and its subclasses' class := Collection. SystemNavigation default browseMessageList: (class withAllSubclasses gather: [:each | each methodDict associations select: [:assoc | assoc value sendsToSuper] thenCollect: [:assoc | MethodReference class: each selector: assoc key]]) name: 'Supersends of ', class name, ' and its subclasses'

© Oscar Nierstrasz ST — Reflection Roadmap  Reification and reflection  Introspection —Inspecting objects —Querying code —Accessing run-time contexts  Intercession —Overriding doesNotUnderstand: —Anonymous classes —Method wrappers Selected material by Marcus Denker and Stéphane Ducasse

© Oscar Nierstrasz ST — Reflection Accessing the run-time stack  The execution stack can be reified and manipulated on demand —thisContext is a pseudo-variable which gives access to the stack

© Oscar Nierstrasz ST — Reflection What happens when a method is executed?  We need space for: —The temporary variables —Remembering where to return to  Everything is an Object! —So: we model this space with objects —Class MethodContext ContextPart variableSubclass: #MethodContext instanceVariableNames: 'method closureOrNil receiver' classVariableNames: '' poolDictionaries: '' category: 'Kernel-Methods'

© Oscar Nierstrasz ST — Reflection MethodContext  MethodContext holds all state associated with the execution of a CompiledMethod —Program Counter (pc, from ContextPart) —the Method itself (method) —Receiver (receiver) and the Sender (sender)  The sender is the previous MethodContext —(or BlockContext) —The chain of senders is a stack —It grows and shrinks on activation and return

© Oscar Nierstrasz ST — Reflection Contextual halting  You can’t put a halt in methods that are called often —e.g., OrderedCollection>>add: —Idea: only halt if called from a method with a certain name HaltDemo>>haltIf: aSelector | context | context := thisContext. [context sender isNil] whileFalse: [context := context sender. (context selector = aSelector) ifTrue: [ Halt signal ] ]. NB: Object>>haltIf: in Pharo is similar

© Oscar Nierstrasz ST — Reflection HaltDemo HaltDemo>>foo self haltIf: #bar. ^ 'foo' HaltDemo>>bar ^ (self foo), 'bar' 'foo'HaltDemo new foo HaltDemo new bar

© Oscar Nierstrasz ST — Reflection Roadmap  Reification and reflection  Introspection —Inspecting objects —Querying code —Accessing run-time contexts  Intercession —Overriding doesNotUnderstand: —Anonymous classes —Method wrappers Selected material by Marcus Denker and Stéphane Ducasse

© Oscar Nierstrasz ST — Reflection Overriding doesNotUnderstand:  Introduce a Minimal Object —Wraps a normal object —Does not understand very much —Redefines doesNotUnderstand: —Superclass is nil or ProtoObject —Uses becomeForward: to substitute the object to control

© Oscar Nierstrasz ST — Reflection Minimal Object at Work

Logging message sends with a minimal object © Oscar Nierstrasz ST — Reflection 42 ProtoObject subclass: #LoggingProxy instanceVariableNames: 'subject invocationCount' classVariableNames: '' poolDictionaries: '' category: 'PBE-Reflection' ProtoObject subclass: #LoggingProxy instanceVariableNames: 'subject invocationCount' classVariableNames: '' poolDictionaries: '' category: 'PBE-Reflection' LoggingProxy>>initialize invocationCount := 0. subject := self. LoggingProxy>>initialize invocationCount := 0. subject := self. LoggingProxy>>doesNotUnderstand: aMessage Transcript show: 'performing ', aMessage printString; cr. invocationCount := invocationCount + 1. ^ aMessage sendTo: subject LoggingProxy>>doesNotUnderstand: aMessage Transcript show: 'performing ', aMessage printString; cr. invocationCount := invocationCount + 1. ^ aMessage sendTo: subject Message>>sendTo: receiver ^ receiver perform: selector withArguments: args Message>>sendTo: receiver ^ receiver perform: selector withArguments: args

Using become: to install a proxy © Oscar Nierstrasz ST — Reflection 43 testDelegation | point | point := LoggingProxy new become: point. self assert: point invocationCount = 0. self assert: point + = self assert: point invocationCount = 1. testDelegation | point | point := LoggingProxy new become: point. self assert: point invocationCount = 0. self assert: point + = self assert: point invocationCount = 1. NB: become: will swap the subject variable of the proxy

© Oscar Nierstrasz ST — Reflection Limitations  self problem —Messages sent by the object to itself are not trapped!  Class control is impossible —Can’t swap classes  Interpretation of minimal protocol —What to do with messages that are understood by both the MinimalObject and its subject?

Using minimal objects to dynamically generate code © Oscar Nierstrasz ST — Reflection 45 DynamicAccessors>>doesNotUnderstand: aMessage | messageName | messageName := aMessage selector asString. (self class instVarNames includes: messageName) ifTrue: [self class compile: messageName, String cr, ' ^ ', messageName. ^ aMessage sendTo: self]. super doesNotUnderstand: aMessage DynamicAccessors>>doesNotUnderstand: aMessage | messageName | messageName := aMessage selector asString. (self class instVarNames includes: messageName) ifTrue: [self class compile: messageName, String cr, ' ^ ', messageName. ^ aMessage sendTo: self]. super doesNotUnderstand: aMessage A minimal object can be used to dynamically generate or lazily load code that does not yet exist.

© Oscar Nierstrasz ST — Reflection Roadmap  Reification and reflection  Introspection —Inspecting objects —Querying code —Accessing run-time contexts  Intercession —Overriding doesNotUnderstand: —Anonymous classes —Method wrappers Selected material by Marcus Denker and Stéphane Ducasse

© Oscar Nierstrasz ST — Reflection Message control with anonymous classes  Create an anonymous class —Instance of Behavior —Define controlling methods —Interpose it between the instance and its class

© Oscar Nierstrasz ST — Reflection Selective control

© Oscar Nierstrasz ST — Reflection Anonymous class in Pharo | anonClass set | anonClass := Behavior new. anonClass superclass: Set; setFormat: Set format. anonClass compile: 'add: anObject Transcript show: ''adding '', anObject printString; cr. ^ super add: anObject'. set := Set new. set add: 1. set primitiveChangeClassTo: anonClass basicNew. set add: 2.

© Oscar Nierstrasz ST — Reflection Evaluation  Either instance-based or group-based  Selective control  No self-send problem  Good performance  Transparent to the user  Requires a bit of compilation —(could be avoided using clone as in Method Wrapper)

© Oscar Nierstrasz ST — Reflection Roadmap  Reification and reflection  Introspection —Inspecting objects —Querying code —Accessing run-time contexts  Intercession —Overriding doesNotUnderstand: —Anonymous classes —Method wrappers Selected material by Marcus Denker and Stéphane Ducasse

© Oscar Nierstrasz ST — Reflection Method Substitution First approach:  Add methods with mangled names —but the user can see them Second approach:  Wrap the methods without polluting the interface —replace the method by an object that implements run:with:in:

© Oscar Nierstrasz ST — Reflection MethodWrapper before and after methods A MethodWrapper replaces an original CompiledMethod in the method dictionary of a class and wraps it by performing some before and after actions.

A LoggingMethodWrapper © Oscar Nierstrasz ST — Reflection 54 LoggingMethodWrapper>>initializeOn: aCompiledMethod method := aCompiledMethod. reference := aCompiledMethod methodReference. invocationCount := 0 LoggingMethodWrapper>>initializeOn: aCompiledMethod method := aCompiledMethod. reference := aCompiledMethod methodReference. invocationCount := 0 LoggingMethodWrapper>>install reference actualClass methodDictionary at: reference methodSymbol put: self LoggingMethodWrapper>>install reference actualClass methodDictionary at: reference methodSymbol put: self LoggingMethodWrapper>>run: aSelector with: anArray in: aReceiver invocationCount := invocationCount + 1. ^ aReceiver withArgs: anArray executeMethod: method LoggingMethodWrapper>>run: aSelector with: anArray in: aReceiver invocationCount := invocationCount + 1. ^ aReceiver withArgs: anArray executeMethod: method NB: Duck-typing also requires (empty) flushCache, methodClass:, and selector: methods uninstall is similar …

Installing a LoggingMethodWrapper © Oscar Nierstrasz ST — Reflection 55 logger := LoggingMethodWrapper on: Integer>>#factorial. logger invocationCount. 5 factorial. logger invocationCount. logger install. [ 5 factorial ] ensure: [logger uninstall]. logger invocationCount. 10 factorial. logger invocationCount. logger := LoggingMethodWrapper on: Integer>>#factorial. logger invocationCount. 5 factorial. logger invocationCount. logger install. [ 5 factorial ] ensure: [logger uninstall]. logger invocationCount. 10 factorial. logger invocationCount

Checking Test Coverage © Oscar Nierstrasz ST — Reflection 56 TestCoverage>>run: aSelector with: anArray in: aReceiver self mark; uninstall. ^ aReceiver withArgs: anArray executeMethod: method TestCoverage>>run: aSelector with: anArray in: aReceiver self mark; uninstall. ^ aReceiver withArgs: anArray executeMethod: method TestCoverage>>mark hasRun := true TestCoverage>>mark hasRun := true

© Oscar Nierstrasz ST — Reflection Evaluation  Class based: —all instances are controlled  Only known messages intercepted  A single method can be controlled  Does not require compilation for installation/removal

© Oscar Nierstrasz ST — Reflection What you should know!  What is the difference between introspection and intercession?  What is the difference between structural and Behavioral reflection?  What is an object? What is a class?  What is the difference between performing a message send and simply evaluating a method looked up in a MethodDictionary?  In what way does thisContext represent the run-time stack?  What different techniques can you use to intercept and control message sends?

© Oscar Nierstrasz ST — Reflection Can you answer these questions?  What form of “reflection” is supported by Java?  What can you do with a metacircular architecture?  Why are Behavior and Class different classes?  What is the class ProtoObject good for?  Why is it not possible to become: a SmallInteger?  What happens to the stack returned by thisContext if you proceed from the self halt?  What is the metaclass of an anonymous class?

© Oscar Nierstrasz ST — Reflection 1.60 Attribution-ShareAlike 3.0 Unported You are free: to Share — to copy, distribute and transmit the work to Remix — to adapt the work Under the following conditions: Attribution. You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work). Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under the same, similar or a compatible license. For any reuse or distribution, you must make clear to others the license terms of this work. The best way to do this is with a link to this web page. Any of the above conditions can be waived if you get permission from the copyright holder. Nothing in this license impairs or restricts the author's moral rights. License