PropertyDescriptor.getReadMethod()尝试查找set方法而不是get方法

Yod*_*oda 6 java reflection

我有一节课:

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
} 
Run Code Online (Sandbox Code Playgroud)

在其他类的其他地方我试着通过这个来调用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)
Run Code Online (Sandbox Code Playgroud)

为什么他尝试访问setter而不是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;
        //
    }
Run Code Online (Sandbox Code Playgroud)

arc*_*rcy 3

在我看来,您的 PropertyDescriptor 构造函数接受您的字符串“Id”并尝试找到setId()要使用的字符串,并且没有这样的方法可供它调用。

编辑:这正是发生的事情:查看PropertyDescriptor的源代码

  • 但是,除非目标同时包含该值的 getter 和 setter,否则无法创建 PropertyDescriptor 对象;欢迎您访问您想要的任何一个,但两个都必须存在*如果您以该形式使用构造函数*。PropertyDescriptor 还有其他构造函数,其中一些构造函数不仅允许您指定所使用的 get/set 方法,而且还允许您在属性没有该访问权限时为其中之一指定 null。也许你可以使用其中之一。 (3认同)