2

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?

xjunz
  • 31
  • 4
  • 1
    Well, the sorting is probably done by your IDE. – MC Emperor Jun 21 '22 at 16:17
  • 1
    What makes you think that this image is a direct, unprocessed result of a `getDeclaredFields()` call? Try running `for(var x:System.class.getDeclaredFields())System.out.println(x);` to see that they're not ordered alphabetically. – tevemadar Jun 21 '22 at 16:18
  • 3
    They have to be returned in _some_ order; alphabetical order is one such order. It's just saying don't _rely_ on it being alphabetical order. If you care about them being in a particular order, sort them yourself. – Andy Turner Jun 21 '22 at 16:28
  • Edit your Question to show example code. – Basil Bourque Jun 21 '22 at 17:06
  • @tevemadar Sure I've tried this. It is actually sorted in alpahbetical order. Maybe I should edit my question to clearify this. – xjunz Jun 26 '22 at 16:40
  • They aren't sorted on my JDK13 installation or on Ideone's whatever Java: https://ideone.com/QA98oN - the fields appear in declaration order there. So yes, as what you describe is not considered common, you should include the a class declaration and/or JDK showing the behaviour. – tevemadar Jun 27 '22 at 08:39

1 Answers1

5

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).

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • 1
    I eventually sovled this problem by using an annotation that marks the ordinal of a field, which is inspired by [this answer](https://stackoverflow.com/a/31119425/14506950). – xjunz Jun 26 '22 at 16:48