Chapter 12. Meta-Programming
Meta-programming is formally defined as writing programs that write programs, but the practical definition is much broader. In general, any solution that manipulates code outside “normal” use is considered meta-programming. Meta-programming approaches tend to be more complex than traditional solutions (for example, libraries and frameworks), but because you are manipulating code at a more fundamental level, it makes hard things easier and impossible things merely improbable.
All major modern languages have some level of meta-programming support. Learning the meta-programming facilities of your primary language will save you major effort and open new avenues to finding solutions.
I talk about several examples of meta-programming in this chapter, giving you a flavor in Java, Groovy, and Ruby. Each language’s capabilities are different; the following examples simply show the kinds of problems you can solve using meta-programming.
Java and Reflection
Java’s reflection is robust but limited. You can
certainly call methods with
String representations of
their names, but the security manager won’t allow you to define new
methods or overwrite existing methods at runtime. You can do some of
that with Aspects, but that’s arguably not really Java because it has
its own syntax, compiler, etc.
An example of when you might want to use Java’s reflection is for testing private ...