One of the bests ways to learn how to use the new Java 5 language features is to re-implement something. And this is exactly what Gabriele Carcassi
did when he built a state machine using annotations
about a year ago. He just recently decided to share that experience with us in his blog.
The idea was to create a generic builder to used annotations to create a framework for building the state machine. Each supporting class and method would be annotated to describe the state change. This scheme solved the “what” aspect of the problem. To solve the “how” Gabriele used the Java 1.4 class Proxy.
Since Java 1.4 there is a class called Proxy: it allows you to create a handler that it's called every time a method is called. The handler is passed the method name and the parameters, which allows us to route the call to whatever object-state and add some logic before and after
The first test case is a simple on/off switch. The example is completed with it’s own JUnit test. Once completed, Gabriel starts the lengthy process of explaining just how to build the supporting framework. In the process we see a few best practices in how to annotations in the process.
Notice the use of @SuppressWarnings: if it wasn't there the compiler would complain …. Such warning should be on the deepest possible method as you do not want to accidentally suppress other warnings.
Though functional, the final implementation is still missing a number of elements such as bean like support of state change notifications or support for state change based on return types. However Gabriel is certain that how these could be implemented is now some what obvious.