review

Enum in Java is more powerful than in any other language, which leads to a number of surprising uses. In this article, I’ll list some of the features of EnUms in Java, and then apply them together to form a state machine.

Enum singleton and utility class usage

You can very simply build a singleton or utility class with an enum.




Implement an interface with enum

You can also implement an interface in an enum.





For each enum instance, a different subclass

You can override the methods of an enum instance. This will effectively give an instance of an enum its own implementation.





Implement a state machine with an enum

What you can do with the above technique is create a state-based enum.

In this small example, the parser’s state machine processes the raw XML in a ByteBuffer. Each state has its own way of handling it, and if there is not enough data available, the state machine can come back and fetch more data again. Each transformation between states is defined, and the code for all states is in an enum.



Using this approach, you can create an XML parser that can process the packet in 10 microseconds. Most of the time, it’s as efficient as you need it to be.