Reflection
in Java |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
String
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]); } } }
Object
objectsObject
, an
array can contain references to objects of
different classes
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!"); } } }
/** * An encapsulation of a Customer */ public class Customer { public int id; public String name; }
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()+" > "); } }