Tuesday 12 August 2014

IllegalAccessException

As per javadoc an IllegalAccessException is thrown when an application tries to reflectively create an instance (other than an array), set or get a field, or invoke a method, but the currently executing method does not have access to the definition of the specified class, field, method or constructor.

Example
You need to suppress Java language access checking in order to reflectively invoke a private method, or access a private variable in another class, with setAccessible(true), otherwise IllegalAccessException thrown.

class Employee {
    private int id, age;
    
    int getId(){
        return id;
    }
    
    int getAge(){
        return age;
    }
            
}

import java.lang.reflect.Field;

public class GetFields {
    
   public static void display(Employee emp){
       System.out.println("---------------------------");
       System.out.println("id : " + emp.getId());
       System.out.println("age : " + emp.getAge());
   }
   public static void main(String args[]) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException{
       Employee emp = new Employee();
       Class myClass = emp.getClass();
       
       System.out.println("Setting id");
       Field myField = myClass.getDeclaredField("id");
       myField.setInt(emp, 1);
       display(emp);
   } 
}

When you tries to run the program, runtime throws IllegalAccessException.

Setting id
Exception in thread "main" java.lang.IllegalAccessException: Class GetFields can not access a member of class Employee with modifiers "private"
 at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:101) at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:101)
 at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(AccessibleObject.java:295)
 at java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:287)
 at java.lang.reflect.Field.setInt(Field.java:940)
 at GetFields.main(GetFields.java:16)
Java Result: 1

To access private variables using reflection, refer the below link.






                                                             Home

No comments:

Post a Comment