Set field value


import java.awt.Rectangle;
import java.lang.reflect.Field;

public class Main {

  public static void main(String[] args) {
    Rectangle r = new Rectangle(100, 20);
    System.out.println("original: " + r.toString());
    modifyWidth(r, new Integer(300));
    System.out.println("modified: " + r.toString());
  }

  static void modifyWidth(Rectangle r, Integer widthParam) {
    Field widthField;
    Integer widthValue;
    Class c = r.getClass();
    try {
      widthField = c.getField("width");
      widthField.set(r, widthParam);
    } catch (NoSuchFieldException e) {
      System.out.println(e);
    } catch (IllegalAccessException e) {
      System.out.println(e);
    }
  }
}
Home 
  Java Book 
    Runnable examples  

Reflection Field:
  1. Get all fields
  2. Get all Declared Fields
  3. Get annotations for a Field
  4. Get "public static final" field
  5. Get specific fields
  6. Get Field value by field name
  7. Get fields for super class
  8. Get Inherited Methods and fields
  9. Get Type of the field or return type of a method.
  10. Field modifiers: isSynthetic, isEnumConstant
  11. Set field value
  12. Set null to a field value
  13. Set private field value