Order of Fields returned by Class.getFields()

后端 未结 4 1170
后悔当初
后悔当初 2021-02-19 07:06

Javadoc for Class.getFields() say: \"The elements in the array returned are not sorted and are not in any particular order.\"

Any hints on how the order act

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-19 07:46

    An natural order of properties offers the Ujorm framework with its key-value objects using the readKeys() method. Each item of the result have got similar features like the Field including reading and writting values from/to the object. For example see the next code:

     public class User extends AbstractUjo implements Serializable {
    
         /** Factory */
         private static final KeyFactory f = newFactory(User.class);
         /** Keys: */
         public static final Key PID = f.newKey();
         public static final Key CODE = f.newKey();
         public static final Key NAME = f.newKey();
         public static final Key CASH = f.newKey();
    
         static {
             f.lock();
         }
    
         // Setters:
         public void setPid(Long pid) {
             PID.setValue(this, pid);
         }
    
         public void setCode(Integer code) {
             CODE.setValue(this, code);
         }
    
         public void setName(String name) {
             NAME.setValue(this, name);
         }
    
         public void setCash(Double cash) {
             CASH.setValue(this, cash);
         }
    
         // Getters ...
     }
    

    The natural order of keys can be iterated by:

     for (Key key : new User().readKeys()) {
         System.out.println("Key: " + key);
     }
    

    See the documentation for more information.

提交回复
热议问题