Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
        //
    }
like image 391
Yoda Avatar asked Jan 15 '15 13:01

Yoda


2 Answers

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

like image 107
arcy Avatar answered Nov 02 '22 16:11

arcy


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".

like image 1
Benedikt Gansinger Avatar answered Nov 02 '22 15:11

Benedikt Gansinger