- Forward


Reflection
in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Introduction
Back SMYC Forward
  • Reflection Defined:
    • An object looking at its internal details at runtime (a.k.a., introspection)
  • Reflection in Java:
    • Because Java bytecode is interpreted at runtime, reflection is fairly straightforward
Important Classes
Back SMYC Forward
  • In java.lang:
    • The Class class
  • In java.lang.reflect:
    • The Field class
    • The Method class
    • The Modifier class
An Important Method
Back SMYC Forward
  • In the Object class:
    • public Class getClass()
  • Purpose:
    • Returns the Class of the Object
An Example
Back SMYC Forward

Using Reflection on a String

javaexamples/reflection/Example1.java
 
Using Reflection with Arrays
Back SMYC Forward
  • Review of Arrays:
    • An array contains a fixed and known number of homogeneous elements
    • An array (normally) is a contiguous block of memory
  • Arrays in Java:
    • An array is an object
    • The elements are (references of) Object objects
    • Since all classes extend Object, an array can contain references to objects of different classes
Using Reflection with Arrays (cont.)
Back SMYC Forward

Using Reflection with an Array of References to Objects in Different Classes

javaexamples/reflection/Example2.java
 
Using Reflection with Arrays (cont.)
Back SMYC Forward
  • An Observation:
    • You will see many examples of this kind, and many people advocating its use
  • The State of the Practice:
    • This is an inappropriate practice
Using Reflection for Serialization
Back SMYC Forward
  • An Observation:
    • At runtime, an object can look at its internal structure in order to "freeze" it
  • A Cautionary Note:
    • As we noted in our discussion of serialization, this can be more complicated than it seems
Using Reflection for Serialization
Back SMYC Forward

Serializing a Simple Class in XML

javaexamples/reflection/Customer.java
 
javaexamples/reflection/XMLWriter.java
 
Some Other Uses of Reflection
Back SMYC Forward
  • Plug-Ins/Extensibility (including Servlets)
  • Creating Decorators
There's Always More to Learn
Back -