Order of Fields returned by Class.getFields()

后端 未结 4 1181
后悔当初
后悔当初 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
    2021-02-19 07:32

    On my JVM, at least,

    Class.getFields() returns fields in declaration order.

    Class.getMethods(), on the other hand, doesn't always. It returns them in (I believe) the order the classloader sees the strings. So if two classes have the same method name, the second-loaded class will return the shared method name before its other methods.

    javap confirms the compiler wrote both fields and methods in declaration order.

    See the output of this code sample.

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

    on my JVM (1.7.0_45, Windows) this returns

    foo
    bar
    bar
    foo
    getFoo
    getBar
    getFoo
    getBar
    

提交回复
热议问题