πŸŽ‰ Special Offer !    Code: GET300OFF    Flat β‚Ή300 OFF on every Java Course
Grab Deal πŸš€

Access Control in Java Reflection  


Introduction
  • By Default:
    • We cannot access private fields, methods, or constructors of another class directly.
    • Even if we try to access private members using Reflection without any special permission, it will throw an IllegalAccessException.
  • But we can bypass Java's access control checks and access private members of any class.
  • For this, Java Reflection provides the setAccessible(true) method which can be called on Field, Method and Constructor objects.
  • So, Access Control in Reflection API decides whether our code can access fields, methods or constructors of a class, especially private ones.
Program:
  • Program 1: Accessing a private field with and without setAccessible(true)
    import java.lang.reflect.*;
    
    class Demo
    {
        private String secret = "This is private";
    
        private void showSecret()
        {
            System.out.println("Secret: " + secret);
        }
    }
    
    public class MainApp
    {
        public static void main(String[] args) throws Exception
        {
            Demo obj = new Demo();
            Class<?> c = obj.getClass();
    
            // Try to access private field without setAccessible()
            Field f = c.getDeclaredField("secret");
    
            try
            {
                System.out.println(f.get(obj)); // ❌ Throws IllegalAccessException
            }
            catch (IllegalAccessException e)
            {
                System.out.println("Cannot access private field without setAccessible(true)");
            }
    
            // Now bypass access control
            f.setAccessible(true); // βœ… Disables access checks
            System.out.println("Private Field Value: " + f.get(obj)); // Works fine
        }
    }
  • Program 2: Accessing both a private field and a private method using setAccessible(true)
    import java.lang.reflect.*;
    
    class Student
    {
        private String name = "Deepak";
    
        private void showMessage()
        {
            System.out.println("Hello from private method!");
        }
    }
    
    public class MainApp
    {
        public static void main(String[] args) throws Exception
        {
            Student s = new Student();
            Class<?> c = Student.class;
    
            // Access private field
            Field field = c.getDeclaredField("name");
            field.setAccessible(true); // βœ… bypass access control
            System.out.println("Private Field Value: " + field.get(s));
    
            // Access private method
            Method method = c.getDeclaredMethod("showMessage");
            method.setAccessible(true); // βœ… allow invocation
            method.invoke(s);
        }
    }