This example shows when the java.lang.IllegalAccessException is thrown in your application. When an application tries to reflectively create an instance (other than an array), set or get a field, or invoke a method, if that method is not accessible to your application (probably the modifier is private or not accessible one), then your application will throw java.lang.IllegalAccessException. This exception is extended from java.lang.ReflectiveOperationException.
Lets look at this simple example which throws java.lang. IllegalAccessException.
ClassNewInstanceExample.java
package javabeat.net.lang; /** * java.lang.IllegalAccessException Example * * @author Krishna * */ public class ClassNewInstanceExample { public static void main(String[] args) throws IllegalAccessException, InstantiationException { Class<?> classVar = ExampleClass.class; ExampleClass t = (ExampleClass) classVar.newInstance(); t.testMethod(); } }
ExampleClass.java
package javabeat.net.lang; public class ExampleClass { private ExampleClass(){ } public void testMethod(){ System.out.println("Method 'testMethod' Called"); } }
Exception Trace…
If you run the above program, you will get the following exception trace as the output.
Exception in thread "main" java.lang.IllegalAccessException: Class javabeat.net.lang.ClassNewInstanceExample can not access a member of class infosys.net.lang.ExampleClass with modifiers "private" at sun.reflect.Reflection.ensureMemberAccess(Unknown Source) at java.lang.Class.newInstance(Unknown Source) at javabeat.net.lang.ClassNewInstanceExample.main(ClassNewInstanceExample.java:13)
The solution for this problem is to check the method or constructor whether it has the proper access modifier to access in your application.