|
Breaching Java Rules with Reflection
Continued from page: 1
Kunal Jaggi
Thursday, August 09, 2007
Putting Reflection in action
It's time to hit the ground running! We'll write a simple standalone Java
client which will use the reflection API to call the private pop(int
elementCount) method on the stack class. The following code fragment presents
the Stackmain.java class:
package com.pcquest.medtracker.client;
import com.pcquest.medtracker.model.Patient;
import com.pcquest.medtracker.model.Stack;
import java.lang.reflect.*;
public class Stackmain {
public static void main(String[] args)throws
Exception {
Stack s=new Stack(10);
s.push(new Patient("Samuel","Hoffman"));
s.push(new Patient("Richard","Ryan"));
s.push(new Patient("Steve","Beytel"));
System.out.println("The original list is: " +
s);
Class klass = s.getClass();
Class[] paramTypes = { Integer.TYPE };
Method m = klass.getDeclaredMethod("pop",
paramTypes);
Object[] arguments = { new Integer(2) };
m.setAccessible(true);
m.invoke(s, arguments);
System.out.println("The new list is: "
+ s);
}
}
In the Stackmain class we begin by instantiating the stack initially with 10
elements. Next, we get a Class object. The arguments to any method that is
invoked through reflection is passed as an array of Class object. The
getDeclaredMethod returns all methods declared by one class. In the above code
fragment, we get the private pop(int elementCount) method handler. Then we call
the setAccessible() method, passing 'true' to make it available to the caller
program. Finally, the invoke() method invokes the underlying method represented
by the Method object, on the specified object with specified parameters. The
following screenshot depicts the output.
Conclusion
Reflection is a powerful tool in the hands of a developer with which she can
modify the runtime behavior of applications running in the Java virtual machine.
That said; reflection should only be used by experienced developers. According
to the Sun Java Tutorial, “Reflection is powerful, but should not be used
indiscriminately”. Reflection comes at a cost--non-reflective programs are more
responsive. A security manager can prevent reflexive behavior at runtime. As a
thumb rule, Reflection should only be used by experienced developers as
indiscriminate usage could change semantics of a running application and
introduce side effects. Page(s) 1 2
|