gpt4 book ai didi

java - PropertyDescriptor.getReadMethod() 试图找到 set 方法而不是 get 方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:28:52 24 4
gpt4 key购买 nike

我有一个类:

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);

cClass类型,oObject类型,id > 是我想要的字段。

但我得到了这个异常(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)

为什么他尝试访问 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;
//
}

最佳答案

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

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

关于java - PropertyDescriptor.getReadMethod() 试图找到 set 方法而不是 get 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27964337/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com