Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Class.getDeclaredFields() return members in a consistent order?

The documentation describes the method as:

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

However I am not sure if this implies that the order will not be consistent each time the application invokes the routine.

I am looking for a way to pair a unique ID for each field that is found - but it also needs to be consistent with the next time the application is run, i.e continuously generate the same ID.

I am wanting to just iterate over each Field found and increment a counter per each element iterated. Then assign the ID of the particular element to whatever the counter is equal to, these 'ids' aren't consistent though if the Fields are not returned in a consistent order.

like image 533
Jeremy Avatar asked Aug 20 '13 01:08

Jeremy


2 Answers

However I am not sure if this implies that the order will not be consistent each time the application invokes the routine.

It does not guarantee that it will be consistent over time. But it might be consistent over time.

And the behaviour might be different for different JVM versions or vendors. And it might be affected by unexpected things ... like class unload / reload, or JIT recompilation.

In short, even if your scheme appears to work, it is liable to be fragile. It is unwise to rely on undocumented behaviour.


It also depends on what you mean by "over time". If you mean "over time" within a single run of the application, then it is (IMO) more likely that order will be consistent than if you consider different runs of the application.

Finally, beware of using hashcode() to give you an ordering. Hashcodes can collide, and if you get a collision your ordering will be ambiguous. The probability of a collision is small but not zero, and if your use-case is security related then it would not be difficult for someone with knowledge of the algorithm to manufacture a collision.

like image 171
Stephen C Avatar answered Sep 28 '22 15:09

Stephen C


The order is not required to be stable across runs. However, the field's hashCode() value is defined to be stable (it's documented to always be field.getDeclaringClass().getName().hashCode() ^ field.getName().hashCode()), so you may be able to use that as your ID, with the understanding that the hash code is not guaranteed to be unique.

Alternatively, you may sort the results returned from getDeclaredFields() yourself, using whatever sorting criteria suits you.

like image 44
Chris Jester-Young Avatar answered Sep 28 '22 17:09

Chris Jester-Young