mfulton26
mfulton26

Reputation: 31234

Is there any particular order to the elements in the array returned by `Class.getDeclaredClasses()`?

Class.getDeclaredMethods states the following:

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

Class.getDeclaredClasses, however, does not specify anything about the order of the elements in the returned array.

Is it supposed to return the elements in any particular order? Is there some specification for JRE implementations that would define such?

Upvotes: 1

Views: 161

Answers (1)

Mike Nakis
Mike Nakis

Reputation: 61986

Generally, you can only rely on things that are explicitly stated in the language specification. If something is not explicitly stated in the spec, you cannot assume that it will be in any particular way, even if you observe it being in a certain way, because it may change without a warning in the future.

You might ask, if that's the case, then why does the language spec explicitly void any warranties about Class.getDeclaredMethods()? If absence of guarantees means "no guarantees", then why doesn't the spec simply remain silent about Class.getDeclaredMethods()?

That's because Class.getDeclaredMethods() used to return elements in a particular order, and lots of people relied on that, but then the creators of the language decided to do away with that at some point, (I think it was with Java 7 but my memory might be failing me,) so they had to explicitly state that they were taking that away.

Which serves as a warning that any assumption above and beyond what the spec says is not just something that may hypothetically get you into trouble, it is a real thing which has actually happened and in all likelihood will continue to happen. Be smart. Do not get in trouble.

Upvotes: 3

Related Questions