简体   繁体   English

Java-以声明的顺序反射getDeclaredMethods奇怪的行为

[英]Java - reflection getDeclaredMethods in declared order strange behaviour

This is a strange behavior happening with getDeclaredMethods ,here is the scenario, a class called Entity: 这是getDeclaredMethods发生的奇怪行为,这是场景,一个称为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); 好的,它们是按顺序排列的,那很好,但是当您将refent设置为_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? 所以...为什么setReference在首位? 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 . 您不能使用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. 最好不要完全依赖顺序-或按照您想要的确定性顺序对数组进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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