The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
November 2000



This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.


Amir, It's all security !!!

Posted by Kishori Sharan on November 21, 2000 at 11:49 AM

In line
Iterator i = l.iterator() ;
l.iterator() returns an Object of class ListItr which is a private inner class defined in java.util.LinkedList class. hasNext ( ) is a public method defined in ListItr class which you are trying to invoke. If you say l.hasNext ( ) then it is ok because ListItr implements List interface and once you have the reference of the actual class in interface variable then you can invoke the methods defined in the interface. But thru reflection , as you trying to do , you cannot invoke the method on a private class which is in different package ( I mean java.util and your class where you using reflection) . So, you are getting security error.
I created the same type of interface and inner class and I tried to call a method as you did. What I found is if your interface , Outer class for the Inner class whose method you are calling , and the class in which you are using reflection are in the same package then it works fine. But, as soon as I tried putting them apart in different packages I got Illegal access exception. So, the conclusion is that there is a security check when you are using relection and if your classes are not in the same package then you need to bypass the security and you can do it just by calling setAccessible ( ) method on method object. So just before your last line include this call. Your program will look like
List l = new LinkedList() ;
Iterator i = l.iterator() ;
Method mi = i.getClass().getMethod( "hasNext", null ) ;
m1.setAccessible ( true ) ; // Bypass security check
mi.invoke( i, null ) ;



Sponsored Links

Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us