A tutorial on reflection, with a particular emphasis on Java, with comparisons with C++ and Smalltalk working examples.
The tutorial focuses on four common problems:
- Avoid using instanceof when code must bypass the compiler and virtual machine’s choice of the method to call.
- Create external, user-defined pieces of code loaded, used, and unloaded at run-time.
- Translate data structures or object state into a format that can be stored (file, network...).
- Monitor the execution of a program to understand its behaviour, measure its space and time complexity.
It shows working examples of Java, Smalltalk, and C++ code solving the four common problems through four scenarios:
- Scenario 1: invoke an arbitrary method on an object (see the problems with instanceof and plugins).
- Scenario 2: access the complete (including private) state of an object (see the problem with serialisation).
- Scenario 3: count the number of instances of a class created at runtime (see the problem with debugging/profiling).
- Scenario 4: patch the method of a class to change its behaviour (see the problem with patching).
It also discusses the different kinds of interconnections among objects that are available in common programming languages (linking, forking, subclassing, inter-process communication, and dynamic loading/invoking), some theory about reflection, and specifically the class-loading mechanism of Java.