Java - Reflection Field Reflection

Introduction

A field of a class is represented by an object of the java.lang.reflect.Field class.

The following four methods in the Class class returns information about the fields of a class:

Method
Description
Field[] getFields()

returns all the accessible public fields of the class or interface. The accessible public
fields include public fields declared in the class or inherited from the superclass.
Field[] getDeclaredFields()
returns all the fields that appear in the declaration of the class. It does not include inherited fields.
Field getField(String name)
get the Field object if you know the name of the field.
Field getDeclaredField(String name)
get the Field object if you know the name of the field. It does not include inherited fields.

Demo

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;

interface IConstants {
  int V = 7;// w w  w  .  ja  v a2  s .co m
}

class A implements IConstants {
  private int aPrivate;
  public int aPublic;
  protected int aProtected;
}

class B extends A {
  private int bPrivate;
  public int bPublic;
  protected int bProtected;
}

public class Main {
  public static void main(String[] args) {
    Class<B> c = B.class;

    // Print declared fields
    ArrayList<String> fieldsDesciption = getDeclaredFieldsList(c);

    System.out.println("Declared Fields for " + c.getName());
    for (String desc : fieldsDesciption) {
      System.out.println(desc);
    }

    // Get the accessible public fields
    fieldsDesciption = getFieldsList(c);

    System.out.println("\nAccessible Fields for " + c.getName());
    for (String desc : fieldsDesciption) {
      System.out.println(desc);
    }

  }

  public static ArrayList<String> getFieldsList(Class c) {
    Field[] fields = c.getFields();
    ArrayList<String> fieldsList = getFieldsDesciption(fields);
    return fieldsList;
  }

  public static ArrayList<String> getDeclaredFieldsList(Class c) {
    Field[] fields = c.getDeclaredFields();
    ArrayList<String> fieldsList = getFieldsDesciption(fields);
    return fieldsList;
  }

  public static ArrayList<String> getFieldsDesciption(Field[] fields) {
    ArrayList<String> fieldList = new ArrayList<>();

    for (Field f : fields) {
      // Get the modifiers for the field
      int mod = f.getModifiers() & Modifier.fieldModifiers();
      String modifiers = Modifier.toString(mod);

      // Get the simple name of the field type
      Class<?> type = f.getType();
      String typeName = type.getSimpleName();

      // Get the name of the field
      String fieldName = f.getName();

      fieldList.add(modifiers + " " + typeName + " " + fieldName);
    }

    return fieldList;
  }
}

Result

Exercise