Here would be a simple solution to output the value always in the same order using reflection.
This is not perfect but the idea here is to show how to order the array of fields using something that should remain the same. Here the name.
public static void toArray(Object o){
List<String> list;
list = Arrays
.stream(o.getClass().getDeclaredFields())
.sorted((f1, f2) -> f1.getName().compareTo(
f2.getName())).map(f -> {
try {
return Optional.ofNullable(f.get(o));
} catch (Exception e) {
return Optional.empty();
}
})
.map(opt -> opt.orElse("null"))
.map(Object::toString)
.collect(Collectors.toList());
System.out.println(list);
}
And a quick example
public static void main(String[] args) {
toArray(new TestClass("Foo", 1, 2L));
toArray(new TestClass("Bar", 3, 4L));
toArray(new TestClass(null, 5, 6L));
}
[1, 2, Foo]
[3, 4, Bar]
[5, 6, null]
For a more complete solution, I would use an annotation to set the position of each values but also to be able to ignore some fields.
toArraymethod or something of that sort.Class.getDeclaredFieldjavadoc The elements in the returned array are not sorted and are not in any particular order. Now, I would guess this will depends on the byte-code so on the same version, it is most likely to be OK but in different version, this could change. But you can always sort the fields based on the name first.