Tuesday, 13 October 2015

Accessing private field value in Java using reflection

Accessing private fields value in Java using reflection

1. Call getDeclaredField("privateField") with parameter variable name which will return instance of java.lang.reflect.Field.

2. Call setAccessible(true) on Field instance to make it accessible .

3. Now fetch the private field value using Field.get(String field_name).

import java.lang.reflect.Field;
class PrivateObject1 {
      private String privateField;
      public PrivateObject1(String privateField) {
            this.privateField = privateField;

public class TestReflectionFields {
      public static void main(String[] args) throws
                  IllegalArgumentException, IllegalAccessException {
            PrivateObject1 student = new PrivateObject1("Private Field");
            try {

                   * NoSuchFieldException-if a specified field is not found.
                   * NullPointerException-if name is null.
                   * SecurityException
                  Field privateField =

                  /** SecurityException - if the request is denied. */
                   * IllegalAccessException-if the field is inaccessible.
                   * IllegalArgumentException
                   * NullPointerException-if the specified object is null and
                                     the field is an instance field.
                   * ExceptionInInitializerError-if the initialization
                                      provoked by this method fails.
                  String fieldValue = (String) privateField.get(student);
                  System.out.println("using reflection#"+fieldValue+" #accessed!");

            } catch (SecurityException e ) {
            } catch (NoSuchFieldException e) {
Output: using reflection # Private Field #accessed !

If you try to access private field without calling setAccessible(true) method, there will be IllegalAccessException.

Exception in thread "main" java.lang.IllegalAccessException: Class core.reflection.TestReflectionFields cannot access a member of class core.reflection.PrivateObject1 with modifiers "private"
      at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:65)
      at java.lang.reflect.Field.doSecurityCheck(Field.java:960)
      at java.lang.reflect.Field.getFieldAccessor(Field.java:896)
      at java.lang.reflect.Field.get(Field.java:358)
      at core.reflection.TestReflectionFields.main(TestReflectionFields.java:33)

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...