log8430 architecture logicielle et conception avanc e
play

LOG8430 : Architecture logicielle et conception avance Yann-Gal - PowerPoint PPT Presentation

LOG8430 : Architecture logicielle et conception avance Yann-Gal Guhneuc Bibliothques et le chargement de composantes dynamiques (Contributeurs : Guhneuc 2009-2015 ; Khomh 2009-2014 ; Soh 2012-2014) This work is licensed under a


  1. Interconnections package kr.ac.yonsei.cse3009.rpc; package kr.ac.yonsei.cse3009.rpc; import org.apache.xmlrpc.server.PropertyHandlerMapping; import java.net.URL; import org.apache.xmlrpc.server.XmlRpcServer; import org.apache.xmlrpc.client.XmlRpcClient; import org.apache.xmlrpc.webserver.WebServer; import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; public class Server { public class Client { public static void main(final String[] args) public static void main(final String[] args) throws Exception { throws Exception { final WebServer webServer = new WebServer(8080); final XmlRpcClientConfigImpl config = final XmlRpcServer xmlRpcServer = new XmlRpcClientConfigImpl(); webServer.getXmlRpcServer(); config.setServerURL( final PropertyHandlerMapping phm = new URL("http://127.0.0.1:8080/xmlrpc")); new PropertyHandlerMapping(); final XmlRpcClient client = new XmlRpcClient(); phm.addHandler("Calculator", Calculator.class); xmlRpcServer.setHandlerMapping(phm); client.setConfig(config); webServer.start(); final Object[] params = new Object[] { } new Integer(33), new Integer(9) }; } final Integer result = (Integer) client.execute("Calculator.add", params); System.out.println(result); } package kr.ac.yonsei.cse3009.rpc; } public class Calculator { public int add(final int i1, final int i2) { return i1 + i2; } public int sub(final int i1, final int i2) { return i1 - i2; } } 23/182

  2. Interconnections � Subclassing public class OutputMonitor extends Thread { ... public OutputMonitor(...) { – Typical in most object- this .setName(threadName); this .setPriority(Thread.MAX_PRIORITY); oriented languages ... } – Structural, static relation public void run() { try { int value = 0; byte [] bytes; char lastWrittenChar; while ((value = this .inputStream.read()) > 0) { synchronized (System.err) { synchronized (System.out) { if (value != 13 && value != 10) { lastWrittenChar = ( char ) value; ... }} } } catch ( final IOException ioe) { 24/182 ...

  3. Interconnections � Subclassing – Hooks and templates • Hot spots = hooks • Frozen spots = templates – Hooks are typically abstract methods – Templates typically use hooks 25/182

  4. Interconnections � Subclassing – Hooks and templates • JUnit 26/182

  5. Interconnections public abstract class TestCase extends Assert implements Test { public void runBare() throws Throwable { setUp(); � Template try { runTest(); } finally { tearDown(); } } protected void setUp() throws Exception { } � Hooks protected void tearDown() throws Exception { } ... } 27/182

  6. Interconnections � Subclassing – Heavily used in object-oriented programs – Heavily used in design patterns (Only Singleton does not explicitly use subclassing) • Abstract Factory • Composite • Decorator • Observer • Visitor 28/182

  7. Sous-classage � Patrons de conception [Gamma et al.] – Usine abstraite ( Abstract Factory ) – Adapteur ( Adapter ) – Pont ( Bridge ) – Constructeur ( Builder ) 29/182

  8. Sous-classage � Patrons de conception [Gamma et al.] – Décorateur ( Decorator ) – Méthode usine ( Factory Method ) – Itérateur ( Iterator ) – Observateur ( Observer ) 30/182

  9. Sous-classage � Patrons de conception [Gamma et al.] – Méthode gabarit (Template Method) – Visiteur ( Visitor ) 31/182

  10. Interconnections � Dynamic loading – In different programming languages (but not all), it is the possibility to load , use , and unload a piece of code at runtime – In Java, it is the possibility to load and unload a class and to choose and invoke its methods (and to access its fields…) at runtime 32/182

  11. Interconnections public final class PoorManProfiler { public static void main( final String[] args) { try { final Class toBeRun = Class. forName (args[0]); final Method mainMethod = toBeRun.getMethod("main", new Class[] { String[]. class }); final long startTime = System. currentTimeMillis (); mainMethod.invoke( null , new Object[] { new String[0] }); final long endTime = System. currentTimeMillis (); System.out.println(); System.out.println(endTime - startTime); } catch ( final Exception e) { e.printStackTrace(); } } } � Poor man’s profiler – Calls the main() method of a class whose name is given at runtime , by the user – Displays the time spent in the called method 33/182

  12. Bibliothèques et le chargement de composantes dynamiques Introduction 1. Bibliothèques et cadriciels 2. – Types d’interconnexions – Problèmes légaux – Chargement dynamique Réflexion 3. Théorie 4. – Méta-classes – Protocoles de méta-objets (MOP) – MOP à la compilation, à l’exécution Retour sur le chargement dynamique 5. 34/182

  13. Interconnexions � Problèmes légaux [Daniel M. German and Ahmed E. Hassan ; License Integration Pattern: Dealing with Licenses Mismatches in Component-based Development ; ICSE, May 2009, ACM Press] – Licences • BSD • GPL • Apache • … 35/182

  14. Interconnexions � Problèmes légaux – Une licence est un ensemble de droits – Chaque droit est un ensemble de conjonctions – Exemple • Licence « BSD originale » • Droit de « distribuer des produits dérivés en binaire » • Conjonctions – « La redistribution […] doit reproduire la note de droit d’auteur ci-dessus […] » – « Tous les produits publicitaires doivent inclure […] » – « Ni le nom de l’auteur ni ceux des contributeurs […] » 36/182

  15. Interconnexions � Problèmes légaux – Soit un programme S composé de deux composants C 1 et C 2 – S , C 1 et C 2 ont chacun une licence – Ces licences ne sont compatibles que si leurs droits sont compatibles 37/182

  16. Interconnexions � Problèmes légaux – Exemple • S est MPL 1.1 et C 1 et C 2 sont GPL 2 • GPL 2 stipule que « Tous produits dérivés de C 1 ( C 2 ) doit être sous licence GPL 2 » • S est MPL 1.1, et MPL 1.1 impose aussi que tout produit dérivés de S soit sous MPL1.1 ou futures MPL • L’intégration de C 1 et C 2 dans S est impossible 38/182

  17. Bibliothèques et le chargement de composantes dynamiques Introduction 1. Bibliothèques et cadriciels 2. – Types d’interconnexions – Problèmes légaux – Chargement dynamique Réflexion 3. Théorie 4. – Méta-classes – Protocoles de méta-objets (MOP) – MOP à la compilation, à l’exécution Retour sur le chargement dynamique 5. 39/182

  18. Chargement dynamique � En deux mots – Dans différents langage de programmation (Lisp, C++, Java, Smalltalk…), c’est la possibilité de lier un « bout de code » au programme pendant l’exécution du programme – En Java, c’est la possibilité de lier une classe, créer une instance de cette classe et exécuter une de ces méthodes pendant l’exécution du programme 40/182

  19. Chargement dynamique � Chargeur de classes – Bootstrap : charge les classes de base et les classes des .jar à l’exécution – Application : charge les classes à partir d’un chemin et les classes de votre application � Les classes chargées – java -verbose:class MyClass 41/182

  20. Chargement dynamique � Charger une classe à public final class WrapperMain { public static void main(String[] args) { try { partir de son nom Class toBeRun = Class. forName (args[0]); Method mainMethod = – Classe enveloppante toBeRun.getMethod("main", new Class[] { String[]. class }); ( wrapper ) final long startTime = System. currentTimeMillis (); � Appeler une méthode mainMethod.invoke( null , new Object[] { new String[0] }); de la classe final long endTime = System. currentTimeMillis (); System.out.println(); � Charger une classe vs. System.out.println(endTime - startTime); } Chargeur de classe catch ( final Exception e) { e.printStackTrace( Output. getInstance ().errorOutput()); } } } 42/182

  21. Reflection � Reflection enables dynamic loading – Reflection ⇒ dynamic loading – Dynamic loading ⇒ Reflection ⁄ • Think of dynamically-loaded shared libraries in C-based operating systems, such as AmigaOS, Linux, UN*X, Windows… 43/182

  22. Bibliothèques et le chargement de composantes dynamiques Introduction 1. Bibliothèques et cadriciels 2. – Types d’interconnexions – Problèmes légaux – Chargement dynamique Réflexion 3. Théorie 4. – Méta-classes – Protocoles de méta-objets (MOP) – MOP à la compilation, à l’exécution Retour sur le chargement dynamique 5. 44/182

  23. Reflection � Reflection is the ability of a computer program to examine and modify the structure and behaviour of an object at runtime 45/182

  24. Scenarios � Scenario 1: invoke an arbitrary method on an object (see the problems with instanceof and plugins) – Given a class C – Given an object o , instance of C – Identify all the methods available on o – Invoke a method using its name foo 46/182

  25. Scenarios � Scenario 2: access the complete (including private) state of an object (see the problem with serialisation) – Given an object o , instance of C – Save on disk the complete state of o – Restore from disk the object o at a later time 47/182

  26. Scenarios � Scenario 3: count the number of instances of a class created at runtime (see the problem with debugging/profiling) – Given a class C – Record the number of its instances ever created – Report this number when the program ends 48/182

  27. Scenarios � Scenario 4: patch the method of a class to change its behaviour (see the problem with patching) – Given an object o , instance of C – Without changing o or C – Change the behaviour of o.foo() 49/182

  28. Scenarios Java Smalltalk C++ 50/182

  29. Scenarios – Given a class C – Given an object o , instance of C – Identify all the methods available on o � Scenario 1: – Invoke a method using its name foo public class C { private int i; public C(final int anInt) { this.i = anInt; } public void foo(final String s) { System.out.print(s); System.out.println(this.i); } } 51/182

  30. Scenarios – Given a class C – Given an object o , instance of C – Identify all the methods available on o � Scenario 1: – Invoke a method using its name foo Identify all the methods available on o foo getClass hashCode equals toString notify notifyAll wait wait wait Invoke a method using its name foo This is foo: 42 52/182

  31. Scenarios – Given a class C – Given an object o , instance of C – Identify all the methods available on o � Scenario 1: – Invoke a method using its name foo final C o = new C(42); System.out.println("Identify all the methods available on o"); final Class<?> classOfO = o.getClass(); final Method[] methodsOfC = classOfO.getMethods(); for (int i = 0; i < methodsOfC.length; i++) { final Method method = methodsOfC[i]; System.out.print('\t'); System.out.println(method.getName()); } System.out.println("Invoke a method using its name foo"); final Method fooMethod = classOfO.getMethod("foo", new Class[] { String.class }); fooMethod.invoke(o, new Object[] { "\tThis is foo: " }); 53/182

  32. Scenarios – Given a class C – Given an object o , instance of C – Identify all the methods available on o � Scenario 1: – Invoke a method using its name foo Identify all the methods available on o foo getClass hashCode equals toString notify notifyAll wait wait wait Invoke a method using its name foo This is foo: 42 54/182

  33. Scenarios – Given an object o , instance of C – Save on disk the complete state of o � Scenario 2: – Restore from disk the object o at a later time public class C { private int i; public C() { this(-1); } public C(final int anInt) { this.i = anInt; } public void foo(final String s) { System.out.print(s); System.out.println(this.i); } } 55/182

  34. Scenarios – Given an object o , instance of C – Save on disk the complete state of o � Scenario 2: – Restore from disk the object o at a later time Save on disk the complete state of o i = 42 Restore from disk the object o at a later time This is foo on o2: 43 56/182

  35. Scenarios – Given an object o , instance of C – Save on disk the complete state of o � Scenario 2: – Restore from disk the object o at a later time final C o1 = new C(42); System.out.println("Save on disk the complete state of o"); final Class<?> classOfO = o1.getClass(); final Field[] fieldsOfC = classOfO.getDeclaredFields(); for (int i = 0; i < fieldsOfC.length; i++) { final Field field = fieldsOfC[i]; field.setAccessible(true); System.out.print('\t' + field.getName()); System.out.println(" = " + field.getInt(o1)); } System.out.println("Restore from disk the object o at a later time"); final C o2 = (C) classOfO.newInstance(); final Field fieldiOfC = classOfO.getDeclaredField("i"); fieldiOfC.setAccessible(true); fieldiOfC.setInt(o2, 43); o2.foo("\tThis is foo on o2: "); 57/182

  36. Scenarios – Given an object o , instance of C – Save on disk the complete state of o � Scenario 2: – Restore from disk the object o at a later time Save on disk the complete state of o i = 42 Restore from disk the object o at a later time This is foo on o2: 43 58/182

  37. Scenarios – Given a class C – Record the numbers of its instance ever created � Scenario 3: – Report this number when the program ends public class C { private static int numberOfInstances; public static int getNumberOfInstances() { return C.numberOfInstances; } private int i; public C() { this(-1); } public C(final int anInt) { C.numberOfInstances++; this.i = anInt; } public void foo(final String s) { System.out.print(s); System.out.println(this.i); } } 59/182

  38. Scenarios – Given a class C – Record the numbers of its instance ever created � Scenario 3: – Report this number when the program ends kr.ac.yonsei.it.cse3009.reflection.scenario3.C@150bd4d kr.ac.yonsei.it.cse3009.reflection.scenario3.C@1bc4459 kr.ac.yonsei.it.cse3009.reflection.scenario3.C@12b6651 3 60/182

  39. Scenarios – Given a class C – Record the numbers of its instance ever created � Scenario 3: – Report this number when the program ends public class Main { public static void main(final String[] args) { final C o1 = new C(42); final C o2 = new C(1); final C o3 = new C(100); System.out.println(o1 + "\n" + o2 + '\n' + o3); System.out.println(C. getNumberOfInstances()); } } 61/182

  40. Scenarios – Given a class C – Record the numbers of its instance ever created � Scenario 3: – Report this number when the program ends kr.ac.yonsei.it.cse3009.reflection.scenario3.C@150bd4d kr.ac.yonsei.it.cse3009.reflection.scenario3.C@1bc4459 kr.ac.yonsei.it.cse3009.reflection.scenario3.C@12b6651 3 To fulfill this scenario, we must modify C 62/182

  41. Scenarios � Class Class is a metaclass – It describes other classes � Class Method is a class – It describes methods � Class Field is a class – It describes fields 63/182

  42. Scenarios � Class Class is a metaclass – It allows to reify classes � Class Method is a class – It allows to reify methods, these language constructs become first-class entities � Class Field is a class – It allows to reify fields , these language constructs become first-class entities 64/182

  43. Scenarios � Class Class is a metaclass – It allows to reify classes Reification is the process of making available an implicit � Class Method is a class construct of a language – It allows to reify methods, these language constructs become first-class entities � Class Field is a class – It allows to reify fields, these language constructs become first-class entities 65/182

  44. Scenarios � We never modified class Class – We only used it to obtain the methods and fields declared by particular classes, e.g. , C � We used static fields and methods to count number of instances 66/182

  45. Scenarios – Given an object o , instance of C – Without changing o or C � Scenario 4: – Change the behaviour of o.foo() public interface I { public void foo(final String s); } public class C implements I { private int i; public C(final int anInt) { this.i = anInt; } public void foo(final String s) { System.out.print(s); System.out.println(this.i); } } 67/182

  46. Scenarios – Given an object o , instance of C – Without changing o or C � Scenario 4: – Change the behaviour of o.foo() This is o: 42 Forwarding method: "foo" Original arguments: "This is o: " New arguments: "THIS IS O: " THIS IS O: 42 68/182

  47. Scenarios – Given an object o , instance of C – Without changing o or C � Scenario 4: – Change the behaviour of o.foo() final I o = new C(42); o.foo("This is o: "); final InvocationHandler handler = new InvokationHandler(o); final I proxy = (I) Proxy. newProxyInstance( I.class.getClassLoader(), new Class[] { I.class }, handler); Assert.assertTrue(proxy instanceof I); Assert.assertFalse(proxy instanceof C); Assert.assertTrue(proxy.equals(o)); proxy.foo("This is o: "); 69/182

  48. public class InvokationHandler implements InvocationHandler { private final I i; public InvokationHandler( final I aConcreteImplementationOfI) { Change the behaviour of o.foo() this .i = aConcreteImplementationOfI; Given an object o , instance of C } public Object invoke( final Object aProxy, Without changing o or C final Method aMethod, final Object[] someArgs) throws Throwable { if (aMethod.getName().equals("foo")) { final String arg = (String) someArgs[0]; final String newArg = arg.toUpperCase(); System.out.print("Forwarding method: \""); System.out.print(aMethod.getName()); System.out.print("\"\n\tOriginal arguments: \""); – – – System.out.print(arg); � Scenario 4: System.out.print("\"\n\tNew arguments: \""); Scenarios System.out.print(newArg); System.out.println('\"'); this .i.foo(newArg); return null ; } else { return aMethod.invoke( this .i, someArgs); } } } 70/182

  49. Scenarios – Given an object o , instance of C – Without changing o or C � Scenario 4: – Change the behaviour of o.foo() Properties of the final I o = new C(42); o.foo("This is o: "); proxy ensured by final InvocationHandler handler = new InvokationHandler(o); final I proxy = the Java VM (I) Proxy. newProxyInstance( I.class.getClassLoader(), new Class[] { I.class }, handler); Assert.assertTrue(proxy instanceof I); Assert.assertFalse(proxy instanceof C); Assert.assertTrue(proxy.equals(o)); proxy.foo("This is o: "); 71/182

  50. Scenarios � Smalltalk – Everything is an object – Everything is an object, really s t atic 72/182

  51. Scenarios � Smalltalk – SmalltalkImage is the class that “represent[s] the current image and runtime environment, including system organization, the virtual machine, object memory, plugins, and source files. [Its] instance variable #globals is a reference to the system dictionary of global variables and class names. [Its] singleton instance is called Smalltalk .” 73/182

  52. Scenarios � Smalltalk – Object is “the root class for almost all of the other classes in the class hierarchy. […] Class Object provides default behavior common to all normal objects, such as access, copying, comparison, error handling, message sending, and reflection. Also utility messages that all objects should respond to are defined here.” 74/182

  53. Scenarios � Smalltalk – Class “[adds] instance-specific behavior to various class-describing objects in the system. This typically includes messages for initializing class variables and instance creation messages particular to a class. There is only one instance of a particular Metaclass, namely the class which is being described.” 75/182

  54. Scenarios – Given a class C – Given an object o , instance of C – Identify all the methods available on o � Scenario 1: – Invoke a method using its name foo Object subclass: #C instanceVariableNames: 'i' classVariableNames: '' poolDictionaries: '' category: 'CSE3009'. C class compile: ' newWithi: anInt ^(self new) i: anInt ; yourself.'. C compile: ' foo: aText Transcript show: aText. Transcript show: i. Transcript cr.'. C compile: ' i: anInt i := anInt.'. 76/182

  55. Scenarios – Given a class C – Given an object o , instance of C – Identify all the methods available on o � Scenario 1: – Invoke a method using its name foo Identify all the methods available on o an IdentitySet(#handles: #longPrintString #actionMap #hasContentsInExplorer [...] #foo: [...] #i: [...] #creationStamp) Invoke a method using its name foo This is foo: 42 77/182

  56. Scenarios – Given a class C – Given an object o , instance of C – Identify all the methods available on o � Scenario 1: – Invoke a method using its name foo |o| o := C newWithi: 42. Transcript show: 'Identify all the methods available on o' ; cr. Transcript show: C allSelectors ; cr. Transcript show: 'Invoke a method using its name foo' ; cr. (C compiledMethodAt: #foo:) valueWithReceiver: o arguments: #('This is foo: '). Simple and straightforward 78/182

  57. Scenarios – Given an object o , instance of C – Save on disk the complete state of o � Scenario 2: – Restore from disk the object o at a later time Object subclass: #C instanceVariableNames: 'i' classVariableNames: '' poolDictionaries: '' category: 'CSE3009'. C class compile: ' newWithi: anInt ^(self new) i: anInt ; yourself.'. C compile: ' foo: aText Transcript show: aText. Transcript show: i. Transcript cr.'. C compile: ' i: anInt i := anInt.'. 79/182

  58. Scenarios – Given an object o , instance of C – Save on disk the complete state of o � Scenario 2: – Restore from disk the object o at a later time Save on disk the complete state of o 42 Restore from disk the object o at a later time This is foo on o2: 43 80/182

  59. Scenarios – Given an object o , instance of C – Save on disk the complete state of o � Scenario 2: – Restore from disk the object o at a later time |o1 o2| o1 := C newWithi: 42. Transcript show: 'Save on disk the complete state of o' ; cr. Transcript show: (o1 instVarAt: 1) ; cr. Transcript show: 'Restore from disk the object o at a later time' ; cr. o2 := C new. o2 instVarNamed: 'i' put: 43. o2 foo: 'This is foo on o2: '. Again, simple and straightforward 81/182

  60. Scenarios – Given an object o , instance of C – Save on disk the complete state of o � Scenario 2: – Restore from disk the object o at a later time – Pharo (a recent implementation of Smalltalk) provides is a general object serialiser that can serialise any object 1@2 serializeToFileNamed: 'hello.fuel'. FLMaterializer materializeFromFileNamed: 'hello.fuel' – Uses reflection to implement these methods! 82/182 Thanks to Marcus Denker for pointing out these helper methods

  61. Scenarios – Given a class C – Record the numbers of its instance ever created � Scenario 3: – Report this number when the program ends Object subclass: #C instanceVariableNames: 'i' classVariableNames: 'NumberOfInstances' poolDictionaries: '' category: 'CSE3009'. C class compile: ' newWithi: anInt ^(self new) i: anInt ; yourself.'. C compile: ' foo: aText Transcript show: aText. Transcript show: i. Transcript cr.'. Only difference with C compile: ' i: anInt i := anInt.'. Scenarios 1 and 2 83/182

  62. Scenarios – Given a class C – Record the numbers of its instance ever created � Scenario 3: – Report this number when the program ends C class compile: ' newWithi: anInt ^(self new) i: anInt ; yourself.'. C compile: ' foo: aText Transcript show: aText. Transcript show: i. Transcript cr.'. C compile: ' i: anInt i := anInt.'. Same as Scenarios 1 and 2 84/182

  63. Scenarios – Given a class C – Record the numbers of its instance ever created � Scenario 3: – Report this number when the program ends C class compile: ' initialize NumberOfInstances := 0.'. C class compile: ' new NumberOfInstances := NumberOfInstances + 1. ^ self basicNew initialize.'. C class compile: ' numberOfInstances ^ NumberOfInstances.'. “Write access” to the metaclass 85/182

  64. Scenarios – Given a class C – Record the numbers of its instance ever created � Scenario 3: – Report this number when the program ends |o1 o2 o3| C initialize. o1 := C newWithi: 42. o2 := C newWithi: 1. o3 := C newWithi: 100. Transcript show: o1 ; show: ' ' ; show: o2 ; show: ' ' ; show: o3 ; cr. Transcript show: C numberOfInstances. 86/182

  65. Scenarios – Given a class C – Record the numbers of its instance ever created � Scenario 3: – Report this number when the program ends a C a C a C 3 To fulfill this scenario, we modified C class not C 87/182

  66. Scenarios – Given a class C – Record the numbers of its instance ever created � Scenario 3: – Report this number when the program ends In Smalltalk, each class has one anonymous meta-class, which can be modified • Adding new variables and methods which are thus class variables and class methods • These methods apply on the class, these fields belong to the class (thus unique) 88/182

  67. Scenarios – Given a class C – Record the numbers of its instance ever created � Scenario 3: – Report this number when the program ends a C a C a C 3 – What about a subclass D of C? – How would its instances be counted? 89/182 Thanks to Christophe Dony for suggesting this use of class vs. class instance variables

  68. Scenarios – Given a class C – Record the numbers of its instance ever created � Scenario 3: – Report this number when the program ends – In C++ and Java: static = global final D o4 = new D(); // Eclipse advises to use C to call getNumberOfInstances(). System.out.println(o4); System.out.println(D. getNumberOfInstances ()); • The class variables is shared by all the instances of its declaring class… and its subclasses! 90/182

  69. Scenarios – Given a class C – Record the numbers of its instance ever created � Scenario 3: – Report this number when the program ends – In Smalltalk: class vs. class instance C class instanceVariableNames: 'IndividualClassNumberOfInstances' • Class variable vs. class instance variable – A class variable is shared by all the instance of the class and all the instances of its subclasses – A class instance variable is unique to each class, inherited from the super-class, like instance variables 91/182

  70. Scenarios – Given a class C – Record the numbers of its instance ever created � Scenario 3: – Report this number when the program ends – In Smalltalk: class vs. class instance C subclass: #D instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Ptidej'. D class compile: ' initialize IndividualClassNumberOfInstances := 0.'. D class compile: ' new NumberOfInstances := NumberOfInstances + 1. IndividualClassNumberOfInstances := IndividualClassNumberOfInstances + 1. ^ self basicNew initialize.'. D class compile: ' numberOfInstances ^ NumberOfInstances.'. D class compile: ' individualClassNumberOfInstances ^ IndividualClassNumberOfInstances.'. 92/182

  71. Scenarios – Given a class C – Record the numbers of its instance ever created � Scenario 3: – Report this number when the program ends – In Smalltalk: class vs. class instance | o4 | D initialize. o4 := D new. Transcript show: o4 ; cr. Transcript show: C numberOfInstances ; cr. Transcript show: D numberOfInstances ; cr. Transcript show: D individualClassNumberOfInstances ; cr. a D 4 4 1 93/182

  72. Scenarios – Given a class C – Record the numbers of its instance ever created � Scenario 3: – Report this number when the program ends – In Java: the JVM contains the world • Possible to connect to a JVM using the Java Debug Interface of the Java Platform Debug Architecture • Possible to reify the classes existing in the remote JVM and to obtain their instances com.sun.jdi.ReferenceType.instances(long) • Special feature of the JVM, “outside” of the normal constructs of the language http://stackoverflow.com/questions/1947122/ 94/182 is-there-a-simple-way-of-obtaining-all-object-instances-of-a-specific-class-in-j/1947200#1947200

  73. Scenarios – Given a class C – Record the numbers of its instance ever created � Scenario 3: – Report this number when the program ends – In Smalltalk: the image contains the world Transcript show: (C allInstances size). • Possible to ask it all the instances of a particular class or all the instances currently in memory 95/182 Thanks to Marcus Denker for pointing out this solution

  74. Scenarios – Given an object o , instance of C – Without changing o or C � Scenario 4: – Change the behaviour of o.foo() Object subclass: #C instanceVariableNames: 'i' classVariableNames: '' poolDictionaries: '' category: 'CSE3009'. C class compile: ' newWithi: anInt ^(self new) i: anInt ; yourself.'. C compile: ' foo: aText Transcript show: aText. Transcript show: i. Transcript cr.'. C compile: ' i: anInt i := anInt.'. 96/182

  75. Scenarios – Given an object o , instance of C – Without changing o or C � Scenario 4: – Change the behaviour of o.foo() This is o: 42 Intercepting message send: foo: Original arguments: This is o: New arguments: THIS IS O: THIS IS O: 42 97/182

  76. Scenarios – Given an object o , instance of C – Without changing o or C � Scenario 4: – Change the behaviour of o.foo() Several choices • ObjectWrappers: http://magaloma.seasidehosting.st/ Kernel#ObjectTracer • MethodWrappers: http://pharo.gforge.inria.fr/ PBE1/PBE1ch15.html • Reflectivity: http://scg.unibe.ch/Research/Reflectivity • … 98/182

  77. Scenarios – Given an object o , instance of C – Without changing o or C � Scenario 4: – Change the behaviour of o.foo() Several choices • ObjectWrappers: http://magaloma.seasidehosting.st/ Kernel#ObjectTracer • MethodWrappers: http://pharo.gforge.inria.fr/ PBE1/PBE1ch15.html • Reflectivity: http://scg.unibe.ch/Research/Reflectivity • … 99/182

  78. Scenarios – Given an object o , instance of C – Without changing o or C � Scenario 4: – Change the behaviour of o.foo() | o aWrapper | o := C newWithi: 42. o foo: 'This is o: '. aWrapper := WrapperForC on: o. "o become: aWrapper." aWrapper foo: 'This is o: '. aWrapper xxxUnTrace. 100/182

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend