Java Reflection field get/set private fields

Introduction

Java reflection API allows us to make an inaccessible field accessible.

public void setAccessible(boolean flag)  
public static void setAccessible(AccessibleObject[] array, boolean flag)

The following program illustrates how to make a private field accessible:

import java.lang.reflect.Field;

class X {//from ww  w  .  java2 s  .c o  m
   private final int pf = 123;
}

public class Main {
   public static void main(String args[]) throws Exception {
      X x = new X();
      Class c = x.getClass();
      Field f = c.getDeclaredField("pf");
      f.setAccessible(true);
      System.out.println("pf = " + f.getInt(x));
   }
}



PreviousNext

Related