dump Static Fields from a class and its instance object - Android java.lang.reflect

Android examples for java.lang.reflect:Field Static

Description

dump Static Fields from a class and its instance object

Demo Code


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

import android.util.Log;

public class Main {
  public static final String TAG = "";

  /**//www.j  av a  2  s  . c  o  m
   * @return A string containing the values of all static {@link Field}s.
   */
  public static final String dumpStaticFields(Class<?> mClass, Object mInstance) {
    if (mClass == null || mInstance == null)
      return null;

    String mStr = mClass.getSimpleName() + "\n\n";

    mStr += "STATIC FIELDS\n\n";

    final Field[] mFields = mClass.getDeclaredFields();

    for (final Field mField : mFields) {
      if (isStatic(mField)) {
        mField.setAccessible(true);

        mStr += mField.getName() + " (" + mField.getType() + ") = ";

        try {
          mStr += mField.get(mInstance).toString();
        } catch (Exception e) {
          mStr += "null";
          Log.e(TAG, "Could not get Field `" + mField.getName() + "`.", e);
        }

        mStr += "\n";
      }
    }

    return mStr;
  }

  /**
   * @return True if the {@link Field} is static.
   */
  public final static boolean isStatic(Field field) {
    final int modifiers = field.getModifiers();
    return (Modifier.isStatic(modifiers));
  }
}

Related Tutorials