Extract all inherited fields from class. - Android java.lang.reflect

Android examples for java.lang.reflect:Field

Description

Extract all inherited fields from class.

Demo Code

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.support.annotation.NonNull;

public class Main {
  /** Guard that protects sCache* fields updates. */
  private static final Object sSync = new Object();
  /** Caching of the reflected information. Class-to-fields. */
  private static final Map<Class<?>, List<Field>> sCacheFields = new HashMap<>();

  /**/*  w w  w  .  j  av  a 2  s  . com*/
   * Extract all inherited fields from class. Results are sorted by name.
   *
   * @param type
   *          type to check
   * @return list of found fields.
   */
  @NonNull
  public static List<Field> getAllFields(@NonNull final Class<?> type) {
    if (sCacheFields.containsKey(type)) {
      return sCacheFields.get(type);
    }

    synchronized (sSync) {
      // second try, after LOCK getting
      if (sCacheFields.containsKey(type)) {
        return sCacheFields.get(type);
      }

      final ArrayList<Field> results = new ArrayList<>();
      sCacheFields.put(type, results);

      Class<?> i = type;
      while (i != null && i != Object.class) {
        for (final Field field : i.getDeclaredFields()) {
          if (!field.isSynthetic()) {
            results.add(field);
          }
        }

        i = i.getSuperclass();
      }

      return results;
    }
  }
}

Related Tutorials