簡體   English   中英

Java-以聲明的順序反射getDeclaredMethods奇怪的行為

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

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

和主類:

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

輸出:

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)

好的,它們是按順序排列的,那很好,但是當您將refent設置為_entity.setReference(100); ,輸出:

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)

所以...為什么setReference在首位? 也許是因為它具有價值? 無論我設置了什么字段,如何保持聲明的順序在類文件中的原樣?

無論我設置了什么字段,如何保持聲明的順序在類文件中的原樣?

您不能使用getDeclaredMethods 文檔對此非常清楚:

返回數組中的元素未排序,並且沒有任何特定順序。

對我來說,尚不清楚該順序甚至出現在字節碼中-您可能需要代碼才能確定原始順序。

最好不要完全依賴順序-或按照您想要的確定性順序對數組進行排序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM