简体   繁体   中英

Java - reflection getDeclaredMethods in declared order strange behaviour

This is a strange behavior happening with getDeclaredMethods ,here is the scenario, a class called Entity:

public class Entity {
private Object reference;

/**
 * @return the reference
 */
public Object getReference() {
    return reference;
}

/**
 * @param reference the reference to set
 */
public void setReference(Object reference) {
    this.reference = reference;
}

public Object getReference2() {
    return reference;
}

public void setReference2(Object reference) {
    this.reference = reference;
}
}

And the main class:

public static void main(String Args[]){
    try {
        Entity _entity = new Entity();


        Class _newClass = _entity.getClass();
        Method[] _method = _newClass.getDeclaredMethods();
        for (int i = 0; i < _method.length; i++) {
            System.out.println(_method[i]);
        }


    } catch (IllegalArgumentException | SecurityException ex) {
        Logger.getLogger(MainApp.class.getName()).log(Level.SEVERE, null, ex);
    }
}

Output:

public java.lang.Object Entities.Entity.getReference()
public void Entities.Entity.setReference(java.lang.Object)
public java.lang.Object Entities.Entity.getReference2()
public void Entities.Entity.setReference2(java.lang.Object)

Ok they are in order, thats fine, but this happens when you setRefference to something _entity.setReference(100); , output:

public void Entities.Entity.setReference(java.lang.Object)
public java.lang.Object Entities.Entity.getReference()
public java.lang.Object Entities.Entity.getReference2()
public void Entities.Entity.setReference2(java.lang.Object)

so... why did the setReference go in first place? Maybe because it has a value? How can I keep the declared order as it is in the class file, no matter what fields I set?

How can I keep the declared order as it is in the class file, no matter what fields I set?

You can't, with getDeclaredMethods . The documentation is very clear about this:

The elements in the returned array are not sorted and are not in any particular order.

It's not clear to me that the order is even present in the bytecode - you may need the source code in order to determine the original ordering.

It would be better simply not to rely on the ordering at all though - or sort the array by whatever deterministic order you want to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM