12 Reflection in a modular world
This chapter covers
If you’re working on a Java application, chances are good that you rely on Spring, Hibernate, JAXP, GSON, or the like. What are “the like”? Frameworks that use Java’s reflection API to inspect your code, search for annotations, instantiate objects, or call methods. Thanks to reflection, they can do all that without having to compile against your code.
Moreover, the reflection API allows frameworks to access nonpublic classes and nonpublic members. It has superpowers beyond what’s possible with compiled code, which bounces off of package boundaries if classes or members aren’t public. The thing is that with modules, reflection no longer works out of the box.
Quite the opposite: reflection lost its superpowers and is bound to the exact same accessibility rules as compiled code. It can only access public members of public classes in exported packages. These frameworks, on the other hand, use reflection over fields and methods that often aren’t public and on classes that you may not want to export because they aren’t part of a module’s API. What do you do then? That’s what this chapter is all about!
To get the most out of this chapter, you should