Java Reference
In-Depth Information
Reflection
Chapter2
referredto
reflection
(alsoknownas
introspection
)asathirdformofruntime
type identification (RTTI). Java's Reflection API lets applications learn about loaded
classes,interfaces,enums(akindofclass),andannotationtypes(akindofinterface).It
alsoletsapplicationsloadclassesdynamically,instantiatethem,findaclass'sfieldsand
methods, access fields, call methods, and perform other tasks reflectively.
to load a class and identify all the loaded class's public methods that are annotated
with
@Stub
annotations.Thistoolisoneexamplewhereusingreflectionisbeneficial.
Another example is the
class browser
, a tool that enumerates the members of a class.
Caution
Reflection should not be used indiscriminately. Application performance
suffersbecauseittakeslongertoperformoperationswithreflectionthanwithoutreflec-
tion.Also,reflection-orientedcodecanbehardertoread,andtheabsenceofcompile-
time type checking can result in runtime failures.
The
java.lang
package's
Class
classistheentrypointintotheReflectionAPI,
whosetypesaremainlystoredinthe
java.lang.reflect
package.
Class
isgen-
erically declared as
Class<T>
, where
T
identifies the class, interface, enum, or an-
notationtypethatisbeingmodeledbythe
Class
object.
T
canbereplacedby
?
(asin
Class<?>
) when the type being modeled is unknown.