Java Reference
In-Depth Information
Solution 78: Reflection Infection
The program creates a set with a single element in it, gets an iterator over the set, invokes the
iterator's
hasNext
method reflectively, and prints the result of the method invocation. As the iterator
hasn't yet returned the set's sole element,
hasNext
should return
TRue
. Running the program,
however, tells a different story:
Exception in thread "main" IllegalAccessException:
Class Reflector can not access a member of class HashMap
$HashIterator with modifiers "public"
at Reflection.ensureMemberAccess(Reflection.java:65)
at Method.invoke(Method.java:578)
at Reflector.main(Reflector.java:11)
How can this be? Of course the
hasNext
method is public, just as the exception tells us, and so can
be accessed from anywhere. So why should the reflective method invocation be illegal?
The problem isn't the access level of the method; it's the access level of the type from which the
method is selected. This type plays the same role as the
qualifying type
in an ordinary method
invocation [JLS 13.1]. In this program, the method is selected from the class represented by the
Class
object that is returned by
it.getClass
. This is the dynamic type of the iterator, which
happens to be the private nested class
java.util.HashMap.KeyIterator
. The reason for the
Search WWH ::
Custom Search