Get field value with Reflection

ReturnMethodSummary
Objectget(Object obj)Returns field value
booleangetBoolean(Object obj)Gets field value as boolean.
bytegetByte(Object obj)Gets field value as byte.
chargetChar(Object obj)Gets field value as char.
doublegetDouble(Object obj)Gets field value as double.
floatgetFloat(Object obj)Gets field value as float.
TypegetGenericType()Returns a Type object that represents the declared type for the field represented by this Field object.
intgetInt(Object obj)Gets field value as int.
longgetLong(Object obj)Gets field value as long.
shortgetShort(Object obj)Gets field value as short.

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");
      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.