events
Dynamic proxies are one of those topics along with Reflection (to a lesser extent) that seem like magic in Java. They exist outside of the safe, procedural oriented nature of the language and add useful complexity and color to an otherwise dull language.
What are Dynamic Proxies exactly? Dynamic Proxies allow you to run custom code before, after, (or before and after) other pieces of code. For example:
class Blah {
public void myMethod() { System.out.println("I ran!"); }
}
Say I wanted the above method to run before every call to Math.cos(). So, I would extend a new class from the Proxy class and tell it to intercept calls to Math.cos(). The I could tell it that instead of calling Math.cos() call my code instead. In my Proxy class, I would have the option of calling the original function or not.
Buzzword Bingo
Essentially, we have created a "logger" for Math.cos. Logging is frequently referred to as a "cross cutting concern". I point this out now to perhaps trigger recognition that one of the chief reasons to use Dynamic Proxies is to insert code around methods in an independent fashion without affecting the original code. Dynamic Proxies are basically what AOP frameworks like SpringAOP and Guice use under the hood to provide their functionality. (psst!
Typical use cases for Dynamic Proxies:
- Unit Testing frameworks such as Butterfly Testing tools.
- Event Listeners
- Anything that's a cross cutting concern that you didn't use AOP for, such as usage logging, security, database connectivity.
Rules and Limitations, more to follow
There are rules and limitations to doing the above, but for today, we'll leave it at that.
