12 Reflection in a modular world

 

This chapter covers

  • Opening packages and modules to reflection
  • Combining modules and reflection
  • Alternatives to the reflection API
  • Analyzing and modifying module properties

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

12.1 Why exports directives aren’t a good fit for reflection

12.1.1 Breaking into non-modular code

12.1.2 Forcing the publication of internal types

12.1.3 Qualified exports create coupling to specific modules

12.1.4 No support for deep reflection

12.2 Open packages and modules: Designed for the reflection use case

12.2.1 Opening packages to run-time access

12.2.2 Opening packages for specific modules

12.2.3 Exporting vs. opening packages

12.2.4 Opening modules: Reflection closeout

12.3 Reflecting over modules

12.3.1 Updating reflecting code for modules (or not)

12.3.2 Using variable handles instead of reflection

12.3.3 Analyzing module properties with reflection

12.3.4 Modifying module properties with reflection

12.3.5 Forwarding open packages

12.4 Dynamically creating module graphs with layers

12.4.1 What are layers?

Summary

sitemap