Mauker
Mauker

Reputation: 11497

Is it possible to get class fields in a sorted way?

Might be a silly question, but... From the docs, I know that in java I have this method called getFields() on the java.lang.Class<T> that will return an array of Field objects, and I also know that the results are not sorted in any way at all.

Returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object. The elements in the array returned are not sorted and are not in any particular order. This method returns an array of length 0 if the class or interface has no accessible public fields, or if it represents an array class, a primitive type, or void.

Now what if I wanted to get those fields sorted? Is there a method out there that will return them for me? Or do I have to sort it myself?

From this question I know I can sort them using a Comparator. I just want to know if I really have to do this extra step myself.

Upvotes: 1

Views: 498

Answers (1)

assylias
assylias

Reputation: 328598

Sorting an array of objects based on a property can be written in one line:

Field[] fields = String.class.getDeclaredFields();
Arrays.sort(fields, comparing(Field::getName));

using a static import: import static java.util.Comparator.comparing;.

Upvotes: 2

Related Questions