2

Can someone please explain why Application.class.getDeclaredFields() returns nothing?

Field[] fields = Application.class.getDeclaredFields();

The Field object is empty after the call. Are there any restrictions in java.lang.reflect that prevent this call from returning anything other than null?

Thank you

dsp_user
  • 2,061
  • 2
  • 16
  • 23
  • How/where are you running the code? If it's the stub android.jar you're running against, it won't contain the private fields or public fields annotated with `@hide`. `Application` has only private fields and a `@hide`-annotated field. (4.4.4_r1) – laalto Sep 15 '14 at 18:39
  • I've tried this code on a HTC Wildfire running Android 2.1 as well as on a Samsung Galaxy Core running 4.1.2. – dsp_user Sep 15 '14 at 19:51

1 Answers1

3

This is not a restriction of reflection but is expected behavior of the Reflection API.

getDeclaredFields returns .. all the fields declared [in this type] .. but excludes inherited fields.

getFields returns the public fields of this class and of all its superclasses.

The android.app.Application class declares no fields itself through version 2.3.7 - that is, all fields in Application are inherited. As such it is fitting that result of getDeclaredFields in such an environment is an empty array.

Version 4.x does add a field (or fields) marked with @hide; these should still be accessible via reflection even if not listed in the javadoc/droiddoc output. In this case getDeclaredFields should return the relevant non-inherited fields.

Community
  • 1
  • 1
user2864740
  • 60,010
  • 15
  • 145
  • 220
  • If I use Class.getFields() instead, I get a bunch of constants (static final some type). I'd expect all those constants with getDeclaredFields() plus any remaining private variables(provided that they exist) but getDeclaredFields returns nothing. – dsp_user Sep 15 '14 at 19:52
  • 1
    Thank you both. I run the code again and the method did return 3 fields on the phone running Android 4.1.2. The fields were mLoadedApk, mComponentCallbacks and mActivityLifecycleCallbacks. – dsp_user Sep 15 '14 at 21:03