jeudi 15 janvier 2015

PropertyDescriptor.getReadMethod() tries to find set method instead of get method

I have a class:



public abstract class Produkt extends ObjectPlus implements Serializable {
static int ID = 0;
private int id;

public Produkt() {
super();
id = ID++;
}

public int getId() {
return id;
}
//lot OF OTHER METHODS
}


Somewhere else in other class I try to invoke getId() method on an object to get the id field value by this:


Integer fieldValue = (Integer) new PropertyDescriptor("Id", c).getReadMethod().invoke(o);


c is of type Class, o is of type Object, id is the field I want.


but I get this exception:



java.beans.IntrospectionException: Method not found: setId
at java.beans.PropertyDescriptor.<init>(Unknown Source)
at java.beans.PropertyDescriptor.<init>(Unknown Source)
at pakiet.ObjectPlus.getCurrentId(ObjectPlus.java:143)
at pakiet.ObjectPlus.wczytajEkstensje(ObjectPlus.java:118)
at pakiet.Main.main(Main.java:72)


Why does he try access setter instead of getter?


The full method is:



public static int getCurrentId(Class c){
//jak wczytamy to zeby nowe osoby mialy nadal unikalne ID(wieksze od najwiekszego)
int maxId = Integer.MIN_VALUE;
for (Map.Entry<Class, ArrayList> entry : ekstensje.entrySet()) {
for (Object o : entry.getValue()){
// This method is the dynamic equivalent of the Java language instanceof operator.
if(c.isInstance(o)){
try{
Class<?> clazz = o.getClass();
Integer fieldValue = (Integer) new PropertyDescriptor("Id", c).getReadMethod().invoke(o);

if(fieldValue > maxId)
maxId = fieldValue;

}catch(Exception e){
e.printStackTrace();
}

}
}
}
return maxId + 1;
//
}





Aucun commentaire:

Enregistrer un commentaire