mercredi 18 février 2015

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?






Aucun commentaire:

Enregistrer un commentaire