Java Reflection - Java Field.set(Object obj, Object value)








Syntax

Field.set(Object obj, Object value) has the following syntax.

public void set(Object obj,  Object value)  throws IllegalArgumentException ,   IllegalAccessException

Example

In the following code shows how to use Field.set(Object obj, Object value) method.

//from  w  w w. jav a  2 s .c  om

import java.lang.reflect.Field;


public class Main {
  public static final void main(final String[] args) throws Exception {
    SomeNumbers obj = new SomeNumbers();
    System.out.println("Before: " + obj);
    
    final Integer value = new Integer(0);
    Field[] fields = obj.getClass()
                      .getFields();
    for (int idx = 0; idx < fields.length; idx++) {
      if (fields[idx].getType() == int.class) {
        fields[idx].set(obj, value);
      }
    }
    
    
    System.out.println("After: " + obj);
  }
}


class SomeNumbers {
  public double a = 1.1d;

  public float b = 2.2f;

  public int c = 3;

  protected int e = 4;

  private int f = 5;

  public String toString() {
    return new String("[a=" + a + ", b=" + b + ", c=" + c + ", e=" + e
                      + ", f=" + f + "]");
  }
}