Class.getFields()返回的字段顺序

Class.getFields() Javadoc说:“返回的数组中的元素没有排序,也没有任何特定的顺序。”

有关如何确定订单的任何提示? 有可能当我执行两次这个方法时,我得到不同顺序的字段吗? 换句话说,对于给定的编译类,或者甚至在相同源文件的编译之间,顺序是否稳定?

它应该是稳定的,对于Oracle的JVM,它们的声明顺序,但你不应该依赖它。

您应该根据字段的名称(可能是声明类)而不是位置来查找。

在我的JVM上,至少,

Class.getFields()以声明顺序返回字段。

另一方面,Class.getMethods()并不总是如此。 它返回它们(我相信)类加载器看到字符串的顺序。 因此,如果两个类具有相同的方法名称,则第二个加载的类将在其他方法之前返回共享方法名称。

javap确认编译器按声明顺序编写了两个字段和方法。

请参阅此代码示例的输出。

 import java.lang.reflect.Field; import java.lang.reflect.Method; public class OrderTest { public static void main(String[] args) { // fields are in declaration order for (Field field : C1.class.getDeclaredFields()) { System.out.println(field.getName()); } for (Field field : C2.class.getDeclaredFields()) { System.out.println(field.getName()); } // methods, on the other hand, are not necessarily in declaration order. for (Method method : C1.class.getDeclaredMethods()) { System.out.println(method.getName()); } for (Method method : C2.class.getDeclaredMethods()) { System.out.println(method.getName()); } } } class C1 { public int foo; public int bar; public int getFoo() { return foo; } public int getBar() { return bar; } } class C2 { public int bar; public int foo; public int getBar() { return bar; } public int getFoo() { return foo; } } 

在我的JVM(1.7.0_45,Windows)上返回

 foo bar bar foo getFoo getBar getFoo getBar 

创建一个返回排序列表的辅助方法,并在需要字段列表时使用它。 或者按名称而不是索引查找。

属性的自然顺序使用readKeys()方法为Ujorm框架提供其键值对象。 结果的每个项目都具有类似的function,如字段,包括从/向对象读取和写入值。 例如,请参阅下一个代码:

  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 ... } 

密钥的自然顺序可以通过以下方式迭代:

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

有关更多信息,请参阅文档 。