Reputation: 57
I declared a class like this:
public class Student implements Serializable {
private static final long serialVersionUID = 8010508999597447226L;
public long id;
public String name;
public int age;
public String phone;
public String address;
public static void main(String[] args) {
Field[] fields = Student.class.getFields();
System.out.println("getFields(): " + fields2String(fields));
fields = Student.class.getDeclaredFields();
System.out.println("getDeclaredFields(): " + fields2String(fields));
}
private static String fields2String(Field[] fields) {
if (fields != null) {
StringBuilder sb = new StringBuilder();
for (Field f : fields) {
sb.append(f.getName());
sb.append(",");
}
return sb.toString();
}
return null;
}
}
The main running result is: (the order is same to my Student.java, my expected order)
getFields(): id,name,age,phone,address,
getDeclaredFields(): serialVersionUID,id,name,age,phone,address,
But the same code running on Android (4.1.2 Dalvik JVM), the result fields order is:
07-28 09:54:14.271 5972-5972/com.ex I/System.out: getFields(): address,age,id,name,phone,
07-28 09:54:14.271 5972-5972/com.ex I/System.out: getDeclaredFields(): serialVersionUID,address,phone,name,age,id,
The order is strange, not class order or alphabet order
I noted that the implementation of getDelclaredFields()
in Android is changed (it's native method public native Field[] getDeclaredFields();
). It may be impossible to change the behavior. But I still want to known that how to get the ordered fields result.
Upvotes: 0
Views: 1113
Reputation: 1854
If you need them in a particular order you can use Arrays.sort(). In the example below you would get them sorted by name (note that I'm using a lambda as the comparator):
Arrays.sort(getClass().getDeclaredFields(), (a, b) -> a.getName().compareTo(b.getName()));
Upvotes: 1