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)
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;
//
}
It seems to me that your PropertyDescriptor constructor takes your string "Id" and attempts to find a setId()
to use because of it, and that there is no such method for it to call.
EDIT: that's exactly what's happening: check out the source code for PropertyDescriptor
You can use a different constructor for this purpose, although it's not as clean (you could however wrap it into a helper function):
Method getter = new PropertyDescriptor(property, objectClass, "is" + Character.toUpperCase(property.charAt(0)) + property.substring(1), null).getReadMethod();
Although I'm passing the "is" prefix, this also works for properties with a getter starting with "get". If there is no "is" method then getReadMethod will search for one named "get".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With