Chapter 6. Reflection
Reflection is the term for a set of features that allow a program to examine its own definition. Reflection in Java plays a role in class browsers, object inspectors, debuggers, interpreters, services such as JavaBeans™ and object serialization, and any tool that creates, inspects, or manipulates arbitrary Java objects on the fly.
Reflection was present in Java from the beginning, but the introduction of generics changed it in two important ways, introducing both generics for reflection and reflection for generics.
By generics for reflection, we mean that some of the types used for reflection became generic types. In particular, the class Class became the generic class Class<T>. We previously met these parameterized Class types in “How to Create Arrays”, where we saw the special techniques that class literals and the Object method getClass use to return more precise type information. In this chapter, we will see how generics are used to especially good effect in annotations and explore the consequences of the fact that the type parameter T in Class<T> can only be bound to a reifiable type. Additionally, we’ll present a short library that can help you avoid many common cases of unchecked casts.
By reflection for generics, we mean that reflection returns information about generic types. There are interfaces to represent generic types, including type variables, parameterized types, and wildcard types, and there are methods that get the generic types of fields, ...
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