SlideShare uma empresa Scribd logo
1 de 60
Baixar para ler offline
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.
Reflection allows you to
both examine and alter the
meta-objects of a system.
Using reflection to modify
a running system
requires some care.
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
10.10
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
10.11
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.12
The Essence of a Class
1. A format
— I.e., a number of instance variables and types
1. A superclass
2. A method dictionary
© Oscar Nierstrasz
ST — Reflection
10.13
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
10.14
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
10.15
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
10.16
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
10.17
“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
10.18
pt := 10@3.
pt instVarNamed: 'x'.
pt instVarNamed: 'x' put: 33.
pt
10
33@3
Accessing state
> Object>>instVarNamed: aString
> Object>>instVarNamed: aString put: anObject
> Object>>instVarAt: aNumber
> Object>>instVarAt: aNumber put: anObject
© Oscar Nierstrasz
ST — Reflection
10.19
'hello' class
(10@3) 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
2664
2274
5
Accessing meta-information
> Object>>class
> Object>>identityHash
© Oscar Nierstrasz
ST — Reflection
10.20
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
10.21
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
10.22
become:
> Swap all the pointers from one object to the other and
back (symmetric)
ReflectionTest>>testBecome
| pt1 pt2 pt3 |
pt1 := 0@0.
pt2 := pt1.
pt3 := 100@100.
pt1 become: pt3.
self assert: pt1 = (100@100).
self assert: pt1 == pt2.
self assert: pt3 = (0@0).
© Oscar Nierstrasz
ST — Reflection
10.23
becomeForward:
> Swap all the pointers from one object to the other
(asymmetric)
ReflectionTest>>testBecomeForward
| pt1 pt2 pt3 |
pt1 := 0@0.
pt2 := pt1.
pt3 := 100@100.
pt1 becomeForward: pt3.
self assert: pt1 = (100@100).
self assert: pt1 == pt2.
self assert: pt2 == pt3.
© Oscar Nierstrasz
ST — Reflection
10.24
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.
2
610
0
163
0
9
101
864
2
610
0
163
0
9
101
864
SystemNavigation
© Oscar Nierstrasz
ST — Reflection
26
SystemNavigation default browseAllImplementorsOf: #,SystemNavigation default browseAllImplementorsOf: #,
© Oscar Nierstrasz
ST — Reflection
10.27
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
10.28
Classes are Holders of CompiledMethods
© Oscar Nierstrasz
ST — Reflection
10.29
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
120
© Oscar Nierstrasz
ST — Reflection
10.30
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
10.33
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.34
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
10.35
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
10.36
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
10.37
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
10.38
HaltDemo
HaltDemo>>foo
self haltIf: #bar.
^ 'foo'
HaltDemo>>bar
^ (self foo), 'bar'
'foo'HaltDemo new foo
HaltDemo new bar
© Oscar Nierstrasz
ST — Reflection
10.39
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.40
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
10.41
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 := 1@2.
LoggingProxy new become: point.
self assert: point invocationCount = 0.
self assert: point + (3@4) = (4@6).
self assert: point invocationCount = 1.
testDelegation
| point |
point := 1@2.
LoggingProxy new become: point.
self assert: point invocationCount = 0.
self assert: point + (3@4) = (4@6).
self assert: point invocationCount = 1.
NB: become: will swap the subject variable of the proxy
© Oscar Nierstrasz
ST — Reflection
10.44
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
10.46
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.47
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
10.48
Selective control
© Oscar Nierstrasz
ST — Reflection
10.49
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
10.50
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
10.51
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.52
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
10.53
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.
00
00
66
66
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
10.57
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
10.58
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
10.59
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
http://creativecommons.org/licenses/by-sa/3.0/

Mais conteúdo relacionado

Mais procurados

Mais procurados (6)

SAX PARSER
SAX PARSER SAX PARSER
SAX PARSER
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Concepts
 
Inheritance
InheritanceInheritance
Inheritance
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBC
 
Java Thread
Java ThreadJava Thread
Java Thread
 
Java for beginners
Java for beginnersJava for beginners
Java for beginners
 

Destaque (20)

Stoop 437-proxy
Stoop 437-proxyStoop 437-proxy
Stoop 437-proxy
 
5 - OOP - Smalltalk in a Nutshell (c)
5 - OOP - Smalltalk in a Nutshell (c)5 - OOP - Smalltalk in a Nutshell (c)
5 - OOP - Smalltalk in a Nutshell (c)
 
10 - OOP - Inheritance (a)
10 - OOP - Inheritance (a)10 - OOP - Inheritance (a)
10 - OOP - Inheritance (a)
 
Stoop 440-adaptor
Stoop 440-adaptorStoop 440-adaptor
Stoop 440-adaptor
 
Stoop ed-lod
Stoop ed-lodStoop ed-lod
Stoop ed-lod
 
Stoop 436-strategy
Stoop 436-strategyStoop 436-strategy
Stoop 436-strategy
 
Stoop ed-class forreuse
Stoop ed-class forreuseStoop ed-class forreuse
Stoop ed-class forreuse
 
Stoop 301-internal objectstructureinvw
Stoop 301-internal objectstructureinvwStoop 301-internal objectstructureinvw
Stoop 301-internal objectstructureinvw
 
12 virtualmachine
12 virtualmachine12 virtualmachine
12 virtualmachine
 
05 seaside
05 seaside05 seaside
05 seaside
 
Stoop 422-naming idioms
Stoop 422-naming idiomsStoop 422-naming idioms
Stoop 422-naming idioms
 
10 - OOP - Inheritance (b)
10 - OOP - Inheritance (b)10 - OOP - Inheritance (b)
10 - OOP - Inheritance (b)
 
Double Dispatch
Double DispatchDouble Dispatch
Double Dispatch
 
Debugging VisualWorks
Debugging VisualWorksDebugging VisualWorks
Debugging VisualWorks
 
Stoop metaclasses
Stoop metaclassesStoop metaclasses
Stoop metaclasses
 
Stoop ed-subtyping subclassing
Stoop ed-subtyping subclassingStoop ed-subtyping subclassing
Stoop ed-subtyping subclassing
 
Stoop 423-smalltalk idioms
Stoop 423-smalltalk idiomsStoop 423-smalltalk idioms
Stoop 423-smalltalk idioms
 
Stoop 414-smalltalk elementsofdesign
Stoop 414-smalltalk elementsofdesignStoop 414-smalltalk elementsofdesign
Stoop 414-smalltalk elementsofdesign
 
Stoop 433-chain
Stoop 433-chainStoop 433-chain
Stoop 433-chain
 
12 - Conditions and Loops
12 - Conditions and Loops12 - Conditions and Loops
12 - Conditions and Loops
 

Semelhante a 10 reflection

Semelhante a 10 reflection (20)

08 refactoring
08 refactoring08 refactoring
08 refactoring
 
04 idioms
04 idioms04 idioms
04 idioms
 
Lecture: Reflection
Lecture: ReflectionLecture: Reflection
Lecture: Reflection
 
06 debugging
06 debugging06 debugging
06 debugging
 
Lecture: Reflection
Lecture: ReflectionLecture: Reflection
Lecture: Reflection
 
03 standardclasses
03 standardclasses03 standardclasses
03 standardclasses
 
Refactoring
RefactoringRefactoring
Refactoring
 
Beyond Text - Methods as Objects
Beyond Text - Methods as ObjectsBeyond Text - Methods as Objects
Beyond Text - Methods as Objects
 
ElasticSearch Basics
ElasticSearch BasicsElasticSearch Basics
ElasticSearch Basics
 
11 bytecode
11 bytecode11 bytecode
11 bytecode
 
Seattle Scalability Meetup 6-26-13
Seattle Scalability Meetup 6-26-13Seattle Scalability Meetup 6-26-13
Seattle Scalability Meetup 6-26-13
 
Pavel_Kravchenko_Mobile Development
Pavel_Kravchenko_Mobile DevelopmentPavel_Kravchenko_Mobile Development
Pavel_Kravchenko_Mobile Development
 
Reflection
ReflectionReflection
Reflection
 
Reflection and Context
Reflection and ContextReflection and Context
Reflection and Context
 
Design Pattern Notes: Nagpur University
Design Pattern Notes: Nagpur UniversityDesign Pattern Notes: Nagpur University
Design Pattern Notes: Nagpur University
 
Reflectivity Demo
Reflectivity DemoReflectivity Demo
Reflectivity Demo
 
Stoop 304-metaclasses
Stoop 304-metaclassesStoop 304-metaclasses
Stoop 304-metaclasses
 
Adv DB - Full Handout.pdf
Adv DB - Full Handout.pdfAdv DB - Full Handout.pdf
Adv DB - Full Handout.pdf
 
Nsq.io on Node.js and Shell
Nsq.io on Node.js and ShellNsq.io on Node.js and Shell
Nsq.io on Node.js and Shell
 
Object oriented programming 2 elements of programming
Object oriented programming 2 elements of programmingObject oriented programming 2 elements of programming
Object oriented programming 2 elements of programming
 

Mais de The World of Smalltalk (13)

05 seaside canvas
05 seaside canvas05 seaside canvas
05 seaside canvas
 
01 intro
01 intro01 intro
01 intro
 
Stoop sed-smells
Stoop sed-smellsStoop sed-smells
Stoop sed-smells
 
Stoop sed-sharing ornot
Stoop sed-sharing ornotStoop sed-sharing ornot
Stoop sed-sharing ornot
 
Stoop sed-class initialization
Stoop sed-class initializationStoop sed-class initialization
Stoop sed-class initialization
 
Stoop sed-class initialization
Stoop sed-class initializationStoop sed-class initialization
Stoop sed-class initialization
 
Stoop ed-unit ofreuse
Stoop ed-unit ofreuseStoop ed-unit ofreuse
Stoop ed-unit ofreuse
 
Stoop ed-some principles
Stoop ed-some principlesStoop ed-some principles
Stoop ed-some principles
 
Stoop ed-inheritance composition
Stoop ed-inheritance compositionStoop ed-inheritance composition
Stoop ed-inheritance composition
 
Stoop ed-frameworks
Stoop ed-frameworksStoop ed-frameworks
Stoop ed-frameworks
 
Stoop ed-dual interface
Stoop ed-dual interfaceStoop ed-dual interface
Stoop ed-dual interface
 
Stoop 450-s unit
Stoop 450-s unitStoop 450-s unit
Stoop 450-s unit
 
Stoop 439-decorator
Stoop 439-decoratorStoop 439-decorator
Stoop 439-decorator
 

Último

Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxDhatriParmar
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfChristalin Nelson
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...Nguyen Thanh Tu Collection
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...DhatriParmar
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
DBMSArchitecture_QueryProcessingandOptimization.pdf
DBMSArchitecture_QueryProcessingandOptimization.pdfDBMSArchitecture_QueryProcessingandOptimization.pdf
DBMSArchitecture_QueryProcessingandOptimization.pdfChristalin Nelson
 
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...Nguyen Thanh Tu Collection
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 
Comparative Literature in India by Amiya dev.pptx
Comparative Literature in India by Amiya dev.pptxComparative Literature in India by Amiya dev.pptx
Comparative Literature in India by Amiya dev.pptxAvaniJani1
 
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...HetalPathak10
 
6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroomSamsung Business USA
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17Celine George
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptxmary850239
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFEPART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFEMISSRITIMABIOLOGYEXP
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxMadhavi Dharankar
 

Último (20)

Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdf
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
DBMSArchitecture_QueryProcessingandOptimization.pdf
DBMSArchitecture_QueryProcessingandOptimization.pdfDBMSArchitecture_QueryProcessingandOptimization.pdf
DBMSArchitecture_QueryProcessingandOptimization.pdf
 
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 
Comparative Literature in India by Amiya dev.pptx
Comparative Literature in India by Amiya dev.pptxComparative Literature in India by Amiya dev.pptx
Comparative Literature in India by Amiya dev.pptx
 
Spearman's correlation,Formula,Advantages,
Spearman's correlation,Formula,Advantages,Spearman's correlation,Formula,Advantages,
Spearman's correlation,Formula,Advantages,
 
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
 
6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFEPART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptx
 

10 reflection

  • 2. Birds-eye view © Oscar Nierstrasz ST — Reflection 1.2 Reflection allows you to both examine and alter the meta-objects of a system. Reflection allows you to both examine and alter the meta-objects of a system. Using reflection to modify a running system requires some care. Using reflection to modify a running system requires some care.
  • 3. © 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
  • 4. © 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
  • 5. 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
  • 6. © 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
  • 7. Reflection and Reification © Oscar Nierstrasz ST — Reflection 7
  • 8. © 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
  • 9. © 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
  • 10. © Oscar Nierstrasz ST — Reflection 10.10 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
  • 11. © Oscar Nierstrasz ST — Reflection 10.11 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
  • 12. © Oscar Nierstrasz ST — Reflection 10.12 The Essence of a Class 1. A format — I.e., a number of instance variables and types 1. A superclass 2. A method dictionary
  • 13. © Oscar Nierstrasz ST — Reflection 10.13 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!
  • 14. © Oscar Nierstrasz ST — Reflection 10.14 The Essence of an Object 1. Class pointer 2. Values > Can be special: — SmallInteger — Indexed rather than pointer values — Compact classes (CompiledMethod, Array …)
  • 15. © Oscar Nierstrasz ST — Reflection 10.15 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
  • 16. © Oscar Nierstrasz ST — Reflection 10.16 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
  • 17. Meta-Operations © Oscar Nierstrasz ST — Reflection 10.17 “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
  • 18. © Oscar Nierstrasz ST — Reflection 10.18 pt := 10@3. pt instVarNamed: 'x'. pt instVarNamed: 'x' put: 33. pt 10 33@3 Accessing state > Object>>instVarNamed: aString > Object>>instVarNamed: aString put: anObject > Object>>instVarAt: aNumber > Object>>instVarAt: aNumber put: anObject
  • 19. © Oscar Nierstrasz ST — Reflection 10.19 'hello' class (10@3) 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 2664 2274 5 Accessing meta-information > Object>>class > Object>>identityHash
  • 20. © Oscar Nierstrasz ST — Reflection 10.20 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.
  • 21. © Oscar Nierstrasz ST — Reflection 10.21 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.
  • 22. © Oscar Nierstrasz ST — Reflection 10.22 become: > Swap all the pointers from one object to the other and back (symmetric) ReflectionTest>>testBecome | pt1 pt2 pt3 | pt1 := 0@0. pt2 := pt1. pt3 := 100@100. pt1 become: pt3. self assert: pt1 = (100@100). self assert: pt1 == pt2. self assert: pt3 = (0@0).
  • 23. © Oscar Nierstrasz ST — Reflection 10.23 becomeForward: > Swap all the pointers from one object to the other (asymmetric) ReflectionTest>>testBecomeForward | pt1 pt2 pt3 | pt1 := 0@0. pt2 := pt1. pt3 := 100@100. pt1 becomeForward: pt3. self assert: pt1 = (100@100). self assert: pt1 == pt2. self assert: pt2 == pt3.
  • 24. © Oscar Nierstrasz ST — Reflection 10.24 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
  • 25. 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. 2 610 0 163 0 9 101 864 2 610 0 163 0 9 101 864
  • 26. SystemNavigation © Oscar Nierstrasz ST — Reflection 26 SystemNavigation default browseAllImplementorsOf: #,SystemNavigation default browseAllImplementorsOf: #,
  • 27. © Oscar Nierstrasz ST — Reflection 10.27 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
  • 28. © Oscar Nierstrasz ST — Reflection 10.28 Classes are Holders of CompiledMethods
  • 29. © Oscar Nierstrasz ST — Reflection 10.29 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 120
  • 30. © Oscar Nierstrasz ST — Reflection 10.30 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
  • 32. 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'
  • 33. © Oscar Nierstrasz ST — Reflection 10.33 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
  • 34. © Oscar Nierstrasz ST — Reflection 10.34 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
  • 35. © Oscar Nierstrasz ST — Reflection 10.35 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'
  • 36. © Oscar Nierstrasz ST — Reflection 10.36 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
  • 37. © Oscar Nierstrasz ST — Reflection 10.37 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
  • 38. © Oscar Nierstrasz ST — Reflection 10.38 HaltDemo HaltDemo>>foo self haltIf: #bar. ^ 'foo' HaltDemo>>bar ^ (self foo), 'bar' 'foo'HaltDemo new foo HaltDemo new bar
  • 39. © Oscar Nierstrasz ST — Reflection 10.39 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
  • 40. © Oscar Nierstrasz ST — Reflection 10.40 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
  • 41. © Oscar Nierstrasz ST — Reflection 10.41 Minimal Object at Work
  • 42. 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
  • 43. Using become: to install a proxy © Oscar Nierstrasz ST — Reflection 43 testDelegation | point | point := 1@2. LoggingProxy new become: point. self assert: point invocationCount = 0. self assert: point + (3@4) = (4@6). self assert: point invocationCount = 1. testDelegation | point | point := 1@2. LoggingProxy new become: point. self assert: point invocationCount = 0. self assert: point + (3@4) = (4@6). self assert: point invocationCount = 1. NB: become: will swap the subject variable of the proxy
  • 44. © Oscar Nierstrasz ST — Reflection 10.44 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?
  • 45. 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.
  • 46. © Oscar Nierstrasz ST — Reflection 10.46 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
  • 47. © Oscar Nierstrasz ST — Reflection 10.47 Message control with anonymous classes > Create an anonymous class — Instance of Behavior — Define controlling methods — Interpose it between the instance and its class
  • 48. © Oscar Nierstrasz ST — Reflection 10.48 Selective control
  • 49. © Oscar Nierstrasz ST — Reflection 10.49 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.
  • 50. © Oscar Nierstrasz ST — Reflection 10.50 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)
  • 51. © Oscar Nierstrasz ST — Reflection 10.51 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
  • 52. © Oscar Nierstrasz ST — Reflection 10.52 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:
  • 53. © Oscar Nierstrasz ST — Reflection 10.53 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.
  • 54. 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 …
  • 55. 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. 00 00 66 66
  • 56. 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
  • 57. © Oscar Nierstrasz ST — Reflection 10.57 Evaluation > Class based: — all instances are controlled > Only known messages intercepted > A single method can be controlled > Does not require compilation for installation/removal
  • 58. © Oscar Nierstrasz ST — Reflection 10.58 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?
  • 59. © Oscar Nierstrasz ST — Reflection 10.59 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?
  • 60. © 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 http://creativecommons.org/licenses/by-sa/3.0/

Notas do Editor

  1. Gregor Kiczales, J.Michael Ashley, Luis Rodriguez, Amin Vahdat and Daniel G. Bobrow, “Metaobject protocols: Why we want them and what else they can do,” Object-Oriented Programming: the CLOS Perspective, pp. 101-118, MIT Press, 1993.
  2. http://www.dreamsongs.com/NewFiles/clos-book.pdf
  3. Many code metrics are directly computed by methods of classes
  4. SystemNavigation supports a gamut of standard useful queries
  5. This simple metamodel allows us to navigate through the system. Note the “methodReference” ivar of CompiledMethod
  6. This class will probably be merged with CompiledMethod in the near future.
  7. Here an accessor is generated if the ivar exists but no getter is defined.