Reflection in Java is very powerful feature and allows you to access private method and fields which is not possible by any other means in Java and because of this feature of reflection many code coverage tool, static analysis tool and Java IDE like Eclipse and Netbeans has been so helpful. In last article we have seen details about private keyword in Java and learned why we should always make fields and method private in Java. There we have mentioned that private fields and methods are only accessible in the class they are declared but with reflection you can call private method and access private fields outside the class. In this article we will see simple example of accessing private field using reflection and invoking private method using reflection in Java.
Accessing private fields in Java using reflection
In order to access private field using reflection, you need to know the name of field than by calling getDeclaredFields(String name) you will get a java.lang.reflect.Field instance representing that field. remember using getDclaredFields() method and not getFields() method which returns all non private fields both from sub class and super class. while getDeclaredFields() returns both private and non private fields declared in the class. Once you get the field reference you need to make it accessible by calling Field.setAccessible(true) because you are going to access private field. Now you can get value or private field by calling Field.get(String field_name).if you don't call setAccessible(true) and try to access private field using reflection you will get Exception as shown in below example
Calling private methods in Java using reflection
In our last Java tutorial on Reflection we have seen how to call a method by its String name and we will use that information here for invoking private method. Calling private method using reflection is similar to accessing private fields reflectively. Use getDeclaredMethods(String name, Class
.. parameter) to get declared private method. pass all the argument type needed by method or nothing if method doesn't accept any argument. This will give you instance of java.lang.reflect.Method which can than be used to call private method using reflection, as shown in code example.
Code example of accessing private field and method using reflection
Few old Java article which you may like to read