Java Reflection and Fields

How to handle the fields in a class with the Java Reflection.

There are several methods to fetch methods of a class.

The getFields() method

  • To find the public fields of a class, you must invoke the getFields() method on the Class object.
  • The getFields() method will return an array of public Field objects which also includes those inherited from the super-classes as well.
    Class rectangleClassObject = Rectangle.class;
    Field [] widthField= rectangleClassObject.getFields();

The getField(String name) method

  • To get a specific public field use the the getField(String name) method on the Class object, which returns one Field object.
    Class rectangleClassObject = Rectangle.class;
    Field widthField= rectangleClassObject.getField("width");
    For none public members the getField(String name) throws a NotSuchFieldException, which must be caught or declared.

The getDeclaredFields() method

  • The getDeclaredFields() method on the Class object ignores inherited fields (in superclasses), but returns all public, protected and private data members.
    Class rectangleClassObject = Rectangle.class;
    Field [] widthField= rectangleClassObject.getDeclaredFields();

How do get and set fields value on an object of a class.

The set() and get() methods

  • When you have got the Field object, you can query or modify the value of the field with the set() and get() methods for Class objects. For primitive types you can and use all the setXxx() and getXxx() methods that are available.
    Class rectangleClassObject = Rectangle.class;
    Field widthField= rectangleClassObject.getField("width");
    Rectangle rect = new Rectangle();
    int widthValue=(int)widthField.getInt(rect);
    All the get(), getXxx(), set() and setXxx() methods will throw an IllegalAccessException if you don’t have access to the field (the field is may bee private).

How do we find the modifiers of a field on an object of a class.

The getModifiers() method

  • The getModifiers() method on the Field object returns an int, which defines the modifiers for the field. In the Modifier class you will find several static final fields and methods for decoding the modifier value.
    Class rectangleClassObject = Rectangle.class;
    Field widthField= rectangleClassObject.getField("width");
    // To test the field for a transient modifier
    boolean mod=Modifier.isTransient(widthField.getModifiers()) 

An example where we use the methods mention above.

  • Below is an example that shows how to use these opportunities to investigate all the fields in a class:
    First, we need a class to our analysis:
    package listfields;
    
    import java.awt.Color;
    
    public class Rectangle   {
      public String name;
      protected int length;
      protected int width;
      private Color color;
      public Rectangle() {
        this("undefined", 10, 10, Color.white);
      }
      @Override
      public String toString() {
        return " Name: " + name+", width: " +
                width + ", length: " + length + ", color: " + color;
      }
      public Rectangle(String name, int width, int length, Color color) {
        this.name=name;
        this.length = length;
        this.width = width;
        this.color = color;
      }
      public String getName() {
        return name;
      }
      public void setName(String name) {
        this.name = name;
      }
      public int getLength() {
        return length;
      }
      public void setLength(int length) {
        this.length = length;
      }
      public int getWidth() {
        return width;
      }
      public void setWidth(int width) {
        this.width = width;
      }
      public Color getColor() {
        return color;
      }
      public void setColor(Color color) {
        this.color = color;
      }
    }
    Here are the main class that creates an object of the Rectangle class, which we examine in terms of fields:
    package listfields;
    
    import java.awt.Color;
    import java.lang.reflect.Field;
    import java.lang.reflect.Modifier;
    
    public class Main {
    
      public static void main(String[] args) throws IllegalArgumentException,
              IllegalAccessException, NoSuchFieldException {
        Rectangle rect = new Rectangle("football ground", 60, 100, Color.green);
        System.out.println("Object before any changes:\n" + rect);
        Class rectangleClassObject = rect.getClass();
    
        System.out.println("\nFinding all declared fields and its type:");
        Field[] fields = rectangleClassObject.getDeclaredFields();
        for (Field field : fields) {
          int mod = field.getModifiers();  // get modifiers
          System.out.print("Field: " + Modifier.toString(mod) + " "
                  + field.getType() + " " + field.getName());
          if (Modifier.isPrivate(mod)) {
            // Cannot access private members, only public and protected
            System.out.println();
          } else {
            System.out.println(" - with value:" + field.get(rect));
          }
          // the int.class returns a Class object
          // this is possible for all primitives
          if (field.getType() == int.class) {
            if (field.getName().equals("width")) {
            // example of using one of the setXXX() method
              field.setInt(rect, 20);
            } else {
            // We can also use the wrapper class for primitive
              field.set(rect, new Integer(40));
            }
          }
        }
    
        System.out.println("\nFinding all public fields and its type:");
        Field[] pfields = rectangleClassObject.getFields();
        for (Field field : pfields) {
          int mod = field.getModifiers();
          System.out.println("Field: " + Modifier.toString(mod) + " "
                  + field.getType() + " " + field.getName());
          if (field.getName().equals("name")) {
           // As the field, name, is public we do not get any IllegalAccessException
           field.set(rect, "Handball court");
          }
        }
    
        System.out.println("\nFinding a specific public field and its type:");
        // The next statement will throws a NoSuchFieldException
        // if the field, name, was NOT public
        Field field = rectangleClassObject.getField("name");
        int mod = field.getModifiers();
        System.out.println("Field: " + Modifier.toString(mod) + " "
                + field.getType() + " " + field.getName());
        if (field.getName().equals("name")) {
          field.set(rect, "Handball court");
        }
    
    
        System.out.println("\nObject after any changes:\n"
                + rect);
      }
    }
    The result of this is:
    Object before any changes:
     Name: football ground, width: 60, length: 100, color: java.awt.Color[r=0,g=255,b=0]
    
    Finding all declared fields and its type:
    Field: public class java.lang.String name - with value:football ground
    Field: protected int length - with value:100
    Field: protected int width - with value:60
    Field: private class java.awt.Color color
    
    Finding all public fields and its type:
    Field: public class java.lang.String name
    
    Finding a specific public field and its type:
    Field: public class java.lang.String name
    
    Object after any changes:
     Name: Handball court, width: 20, length: 40, color: java.awt.Color[r=0,g=255,b=0]
    You can download this example here (needed tools can be found in the right menu on this page).
Prev. in menu JavaReflection/Fields.php Next in menu
Prev. in menu JavaReflection/Fields.php Next in menu
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.