1

I just wonder that can we specify the orders of fields of a class?

I have a class (let's say subClass) which extends another class (superCalss).

public class SuperClass {
   Object superClassFiled1;
   Object superClassFiled2;
   Object superClassFiled3;
   ...
}

public class SubClasss extends SuperClass {
   Object subClassField1;
   Object subClassField2;
}

When I print out the subClass, subClass's fields coma first but I nee a special order like that:

{
superClassFiled1 : "someValue",
subClassField1 : "someValue",
subClassField2 : "someValue",
superClassFiled2 : "someValue",
superClassFiled3 : "someValue",
...
}

I use subClass.getFields() to get fields.

Is there any way to order them?

Note: I want to order them before callig subClass.getFields(). I have tried many ways and decided to create a new class which duplicates the fields of the main class. So I ordered the fields in the class.

menoktaokan
  • 346
  • 3
  • 13
  • 1
    The return value of `getFields()` is an array, you can sort it any way you like, see https://stackoverflow.com/questions/8938235/sort-an-array-in-java or https://stackoverflow.com/questions/3077746/how-to-sort-an-array-of-objectspoints-in-java – Progman Sep 22 '21 at 19:43
  • Thank you for your answer. I need a custom sorting which is independent of the values of the fileds. – menoktaokan Sep 23 '21 at 04:29
  • You can use a custom `Comparator` class as mentioned in https://stackoverflow.com/questions/3077746/how-to-sort-an-array-of-objectspoints-in-java to sort the array you have the way you like. – Progman Sep 23 '21 at 16:35
  • I do not interest in arrays. – menoktaokan Sep 24 '21 at 10:27
  • But the `getFields()` method you are using returns an array of `java.lang.reflect.Field` instances. So you could use a `Comparator` to sort the array you have the way you like. However, it is unclear how exactly you want to order the fields. Please [edit] your question to include a detailed description of your logic on how the field should be sorted. Also show your attempts you have tried and the problems/error messages you get from your attempts to sort the fields. If possible provide a [mcve]. – Progman Sep 24 '21 at 17:21
  • Thank you for your interest. I have edited the question. – menoktaokan Sep 27 '21 at 06:46

0 Answers0