Saturday 16 August 2014

Accessing Private Methods

By using reflection, you can access private methods in Java.

Step 1: Get the class object.
Ex: Class myClass = Class.forName("Employee");

Step 2: get the declared method.
Ex: Method myMethod = myClass.getDeclaredMethod("getNoEmployee")

Step 3: suppress Java language access checking by enabling the accessibility to true for this method.
Ex: myMethod.setAccessible(true)

Step 4: Invoke the method.
Ex: myMethod.invoke(emp)

class Employee {
    private int id, age;
    private int count =0;
    
    Employee(){
        count++;
    }
    
    int getId(){
        return id;
    }
    
    int getAge(){
        return age;
    }
    
    private int getNoEmployee(){
        return count;
    }
            
}

import java.lang.reflect.*;

public class GetPrivateMethods {
    public static void main(String args[]) throws Exception{
        Class myClass = Class.forName("Employee");
        Employee emp = new Employee();
        Method myMethod = myClass.getDeclaredMethod("getNoEmployee");
        myMethod.setAccessible(true);
        
        Object result = myMethod.invoke(emp);
        System.out.println(result);
    }
}

Output
1



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment