Java Reflection field get/set field value

Introduction

The class Field has several methods to get and/or set field value.

import java.lang.reflect.Field;

class X {/*ww  w  . ja v  a2  s  .  c  om*/
   public double pd1 = 1;
   public double pd2 = 2;
}

public class Main {
   public static void main(String args[]) throws Exception {
      X x = new X();
      Class c = x.getClass();
      String fname = "pd1";
      Field f = c.getDeclaredField(fname);
      System.out.println("Before, " + fname + ": " + f.getDouble(x));
      f.setDouble(x, 4);
      System.out.println("After, " + fname + ": " + f.getDouble(x));
   }
}



PreviousNext

Related