CS 4773 Object Oriented Systems Java Reflection


This material is taken from Chapter 5 of Core Java volume 1 and the Java documentation

Introduction The reflection API is a toolset for manipulating Java code dynamically.
It allows you to:

The Class class
The java runtime system keeps track of the class to which each object belongs.
You can get this information with the getClass() method:

   Object myObject;
   Class myObjectClass;
   ...
   myObjectClass = myObject.getClass();
You can also get a class from its name:
   Class dateClass = Class.forName("java.util.Date");
Once you have the class, some of the things you can do are:

The Constructor class
An instance of this represents a constructor for a given class.

  • get the name of the constructor
  • get the parameter types of the constructor
  • create a new instance of the class corresponding to this constructor.

    The Method class
    An instance of this represents a method of a given class.
    Having one fo these allows you to:

    Many of the methods in the reflection API throw exceptions when an error occurs.

    Many of the methods in the reflection API take advantage of the new varargs feature of Java 5.

    You have used varargs in C when you have used fprintf or similar functions.

    You use the ellipsis to represent a list of arguments and you can iterate through the list: (From p 189 of Core Java I)

    public static double max(double... values) {
       double largest = Double.MIN_VALUE;
       for (double v : values)
          if (v > largest)
             largest = v;
       return largest;
    }
    
    You can call this as follows:
    double n = max*3.1, 40.4, -5);

    Look at the Java documentation for Class, Constructor, and Method


    How I used reflection in the editor project

    Problem:

    Solution: Original Implementation: Current Implementation: