IllegalAccessException on using reflection

后端 未结 5 773
情书的邮戳
情书的邮戳 2020-12-09 18:05

I was trying to learn reflection and I came across this IllegalAccessException. Please see the following code:

public class ReflectionTest
{
      public sta         


        
5条回答
  •  南方客
    南方客 (楼主)
    2020-12-09 18:44

    The troublesome piece of code is this:

    itr.getClass().getMethod
    

    You probably wanted hasNext on the Iterator class. What you have written is the HashMap.KeyIterator class, which according the Java language access specifiers (or at least the rough interpretation of JDK 1.0 used by reflection) is not available to your code.

    Use instead:

    Iterator.class.getMethod
    

    (And if it wasn't for learning purposes, stay away from reflection.)

提交回复
热议问题