Set field value with Reflection

ReturnMethodSummary
voidset(Object obj, Object value)Sets the field value.
voidsetBoolean(Object obj, boolean z)Sets boolean field value.
voidsetByte(Object obj, byte b)Sets byte field value.
voidsetChar(Object obj, char c)Sets char field value.
voidsetDouble(Object obj, double d)Sets double field value.
voidsetFloat(Object obj, float f)Sets float field value.
voidsetInt(Object obj, int i)Sets int field value.
voidsetLong(Object obj, long l)Sets long field value.
voidsetShort(Object obj, short s)Sets short 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, 325);
    Class c = r.getClass();
    try {
      Field heightField = c.getField("height");
      heightField.setInt(r, 1000);
      Integer heightValue = (Integer) heightField.get(r);
      System.out.println("Height: " + heightValue.toString());
    } catch (NoSuchFieldException e) {
      System.out.println(e);
    } catch (SecurityException e) {
      System.out.println(e);
    } catch (IllegalAccessException e) {
      System.out.println(e);
    }
  }
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.