Search code examples
javareflections

Why Class.getDeclaredFields() are sorted alphabetically unexpectedly?


It is said on the docs of Class.getDeclaredFields() that

The elements in the returned array are not sorted and are not in any particular order.

But I found that the results are actually sorted in perfect alphabetical order instead of the declration order. So what's going on? My JDK version is 1.8.

PS: I wonder this because I am now implementing a way of object serialization relying on the declaration order of the declared fields, which is not affected by code obfuscation. Is there any better idea to do this?


Solution

  • getDeclaredFields returns an array, so the elements have to be in some order. What the docs mean here is that the elements of the array are not guaranteed to be in any particular order, whether it be alphabetical or declaration order. In other words, the implementation can return the fields in any order it like. It is an implementation detail.

    The JVM that you are using to run the program might return them in alphabetical order. Another JVM might return them in declaration order.

    Getting the declaration order of fields is impossible, unless you do tap into the compiler's compilation process or something overkill like that. Alternatively, if you assume that the order of the fields remain the same when they are written to the class file, you can read the class file and get the fields in order (see this answer for a link to code).