CS 451 - Programming Languages - Fall 2007
Java Reflection
Loyola College >
Department of Computer Science >
Dr. James Glenn >
CS 451 >
Lecture Notes and Examples >
Java Reflection
Reflection.java
/*
<APPLET CODE="Reflection.class" WIDTH=400 HEIGHT=100></APPLET>
*/
import java.awt.*;
import javax.swing.*;
import java.lang.reflect.*;
/**
* An example of using reflection in Java.
*
* @author Jim Glenn
* @version 0.1 10/15/2007 Beware?
*/
public class Reflection extends JApplet
{
public void paint(Graphics g)
{
g.drawString("The easy way", 20, 20);
try
{
Class gClass = Graphics.class; // the Class object for Graphics
// set up the argument list for getMethod (the list
// of Classes of arguments for the method we're trying
// to get
Class[] drawArgs = new Class[3];
drawArgs[0] = String.class;
drawArgs[1] = int.class;
drawArgs[2] = int.class;
Method draw = gClass.getMethod("drawString", drawArgs);
// or could use variable argument lists:
// draw = gClass.getMethod("drawString", String.class, int.class, int.class);
// just for fun, we'll invoke Math.max(20, 40) using
// reflection to compute the y-value for our second
// string
Method max = Math.class.getMethod("max", int.class, int.class);
// note the autoboxing for the arguments to invoke; the
// return value can't be unboxed until it is cast from Object
int xPos = 20;
int yPos = (Integer)(max.invoke(null, 40, xPos));
draw.invoke(g, "The hard way", xPos, yPos);
// draw.invoke(g, new Object[] {"The hard way", xPos, yPos});
}
catch (NoSuchMethodException e)
{
// would get here if either getMethod invocation failed
e.printStackTrace(System.err);
}
/*
catch (SecurityException e) // optional catch block
{
// reflection can't get around access restrictions
// (protected/private/package) or security restructions
// (applet restrictions, etc.)
e.printStackTrace(System.err);
}
*/
catch (IllegalAccessException e)
{
// see above
e.printStackTrace(System.err);
}
/*
catch (IllegalArgumentException e) // optional catch block
{
// invoke checks argument lists (including the first
// argument passed as this) just like the compiler does
e.printStackTrace(System.err);
}
*/
catch (InvocationTargetException e)
{
// the method invoke invoked might throw an exception;
// we could access that exception here
e.printStackTrace(System.err);
}
}
}
This code can also be downloaded from the file
Reflection.java.