propertydescriptor.getreadmethod()尝试查找set方法而不是get方法

o0lyfsai  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(291)

我有一门课:

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
}

在我试图调用的其他类的其他地方 getId() 方法来获取 id 字段值:
Integer fieldValue = (Integer) new PropertyDescriptor("Id", c).getReadMethod().invoke(o); c 属于类型 Class , o 属于类型 Object , id 是我想要的领域。
但我有个例外:

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)

为什么他要尝试accesssetter而不是getter?

完整的方法是:

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;
        //
    }
z6psavjg

z6psavjg1#

为此,您可以使用不同的构造函数,尽管它没有那么干净(但是您可以将其 Package 到一个helper函数中):

Method getter = new PropertyDescriptor(property, objectClass, "is" + Character.toUpperCase(property.charAt(0)) + property.substring(1), null).getReadMethod();

虽然我传递的是“is”前缀,但这也适用于getter以“get”开头的属性。如果没有“is”方法,那么getreadmethod将搜索一个名为“get”的方法。

fslejnso

fslejnso2#

在我看来,propertydescriptor构造函数接受字符串“id”并尝试查找 setId() 因为它而使用,并且没有这样的方法供它调用。
编辑:这正是发生的事情:查看propertydescriptor的源代码

相关问题