Putting Reflection to Work
We’ve discussed reflection largely in terms of how design tools use it to analyze your classes. But it would be a shame to end this discussion without showing you how to use reflection for your own purposes. It’s a powerful tool that lets you do many things that wouldn’t be possible otherwise. In this section, we’ll build a dynamic event adapter that can be configured at runtime.
In Chapter 13, we saw how adapter classes could be built to connect event firings to arbitrary methods in our code, allowing us to cleanly separate GUI and logic in our applications. In this chapter, we have described how the BeanBox interposes adapters between Beans to do this for us. We have also described how the BeanBox uses adapters to bind and constrain properties between Beans.
One of the primary motivations behind the AWT/Swing event model was to reduce the need to subclass components to perform simple hookups. But if we start relying heavily on special adapter classes, we can quickly end up with as many adapters as objects. Anonymous inner classes let us hide the existence of these classes, but they’re still there. A potential solution for large or specialized applications is to create generic event adapters that can serve a number of event sources and targets simultaneously.
The following example,
DynamicActionAdapter
, is a generic adapter for
ActionEvents. A single instance of
DynamicActionAdapter can be used to hook up a
number of ActionEvent sources.
DynamicActionAdapter ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access