java.lang.IllegalAccessException while using reflection in java


In this Example we are going to understanding the exception while using reflection.

Error Message :
Exception in thread "main" java.lang.IllegalAccessException: class com.si.exceptions.IllegalAccessExceptionSample cannot access a member of class java.util.ArrayList$Itr (in module java.base) with modifiers "public"
       at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException(Reflection.java:355)
       at java.base/java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:639)
       at java.base/java.lang.reflect.Method.invoke(Method.java:559)
       at com.si.exceptions.IllegalAccessExceptionSample.main(IllegalAccessExceptionSample.java:17)

Error Description :

package com.si.exceptions;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class IllegalAccessExceptionSample {

       public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

                     List<String> list = new ArrayList<String>();
                     list.add("First");
                     Iterator it = list.iterator();
                     Method m = it.getClass().getMethod("hasNext");
                     System.out.println(m.invoke(it));
       }
}

In the above example ,the red background color line is giving the exception.
Here The Method does not have access to the method named hasNext, e.g., by it being private or protected. So we can not access this calss using the way above yellow color code.

Solution:


To avoid this exception , we use directly Iterator class method using the green color code as shown below.

package com.si.exceptions;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class IllegalAccessExceptionSample {

       public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

                     List<String> list = new ArrayList<String>();
                     list.add("First");
                     Iterator it = list.iterator();
                     Method m = Iterator.class.getMethod("hasNext");
                     System.out.println(m.invoke(it));
       }
}
                         
Output:

true
Share this post :

Post a comment

Please share your valuable feedback and share this article in social media.

 
Support : Ranga Rajesh Kumar
Copyright © 2019. Error Solution - All Rights Reserved
Site Designed by Ranga Rajesh Kumar