JMU
Reflection
in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Introduction
Important Classes
An Important Method
An Example

Using Reflection on a String

javaexamples/reflection/Example1.java
import java.lang.reflect.*;

/**
 * A simple example that uses reflection
 *
 * @author  Computer Science Deprtment, James Madison University
 * @version 1.0
 */
public class Example1
{
    /**
     * The entry point
     *
     * @param args   The command-line arguments
     */
    public static void main(String[] args)
    {
       Class         s_Class;
       Field[]       s_Fields;
       int           i;
       Method[]      s_Methods;
       String        s;



       s = new String();

       // Get the Class of s
       s_Class = s.getClass();
       System.out.println(s_Class);


       // Get the fields/attributes  of s
       s_Fields = s_Class.getDeclaredFields();

       for (i=0; i < s_Fields.length; i++) 
       {
          System.out.println(s_Fields[i]);
       }


       // Get the methods of s
       s_Methods = s_Class.getDeclaredMethods();

       for (i=0; i < s_Methods.length; i++) 
       {
          System.out.println(s_Methods[i]);
       }
    }
}
        
Using Reflection with Arrays
Using Reflection with Arrays (cont.)

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

javaexamples/reflection/Example2.java
import java.awt.Color;
import java.lang.reflect.*;
import java.util.Hashtable;

/**
 * A simple example that uses reflection
 *
 * @author  Computer Science Deprtment, James Madison University
 * @version 1.0
 */
public class Example2
{
    /**
     * The entry point
     *
     * @param args   The command-line arguments
     */
    public static void main(String[] args)
    {
       Object[]      list;


       list    = new Object[3];
       list[0] = new String("Fred");
       list[1] = new Hashtable();
       list[2] = new Color(255, 0, 0);

       handleList(list);
    }



    /**
     * Handle a generic list of objects
     *
     * @param  list   The list of objects
     */
    public static void handleList(Object[] list)
    {
       Class    c, colorClass, stringClass;
       int      i;

       try 
       {
          colorClass  = Class.forName("java.awt.Color");
          stringClass = Class.forName("java.lang.String"); 

          for (i=0; i < list.length; i++) 
          {
             c = list[i].getClass();
             if (c.equals(colorClass)) 
             {
                System.out.println("Handling a Color.");
             } 
             else if  (c.equals(stringClass)) 
             {
                System.out.println("Handling a String");
             } 
             else 
             {
                System.out.println("I don't know what to do.");
             }
          }
       } 
       catch (ClassNotFoundException cnfe)
       {
          System.out.println("Big trouble!");
       }
    }
}
    
        
Using Reflection with Arrays (cont.)
Using Reflection for Serialization
Using Reflection for Serialization

Serializing a Simple Class in XML

javaexamples/reflection/Customer.java
/**
 * An encapsulation of a Customer
 */
public class Customer
{
    public int      id;
    public String   name;

}
        
javaexamples/reflection/XMLWriter.java
import java.lang.reflect.*;

/**
 * Uses reflection to write an XML
 * representation of simple objects
 *
 * @author  Computer Science Deprtment, James Madison University
 * @version 1.0
 */
public class XMLWriter
{
    /**
     * Write the object
     *
     * @param obj   The Object
     */
    public void write(Object obj) throws Exception
    {
        Class         obj_Class;
        Field[]       obj_Fields;
        int           i;


        obj_Class = obj.getClass();
        System.out.println(" < "+obj_Class.getName()+" > ");

        obj_Fields = obj_Class.getDeclaredFields();
        for (i=0; i < obj_Fields.length; i++) 
        {
            System.out.print(" < "+obj_Fields[i].getName()+" > ");
            System.out.print(obj_Fields[i].get(obj));
            System.out.print(" </ "+obj_Fields[i].getName()+" > \n");
        }
        System.out.println(" </ "+obj_Class.getName()+" > ");
    }

}
        
Some Other Uses of Reflection