我有一节课:
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)
完整的方法是:
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)
在我看来,您的 PropertyDescriptor 构造函数接受您的字符串“Id”并尝试找到setId()要使用的字符串,并且没有这样的方法可供它调用。
编辑:这正是发生的事情:查看PropertyDescriptor的源代码
| 归档时间: |
|
| 查看次数: |
3338 次 |
| 最近记录: |