gpt4 book ai didi

java - 反射调用抛出 IllegalArgumentException

转载 作者:行者123 更新时间:2023-12-01 22:04:52 28 4
gpt4 key购买 nike

我在这里缺少什么?

我得到异常:java.lang.IllegalArgumentException:对象不是声明类的实例

public boolean onSave(Object entity,Serializable id,Object[] state, String[] propertyNames, Type[] types) {
Class<?> clazz=entity.getClass();
System.out.println(" Clazzz is:"+clazz);
Method[] methods = clazz.getMethods();

for(Method method : methods){
if(method.getName().startsWith("get") && String.class.equals(method.getReturnType())){
System.out.println("getter: " + method);

try {
String s=(String) method.invoke(clazz,(Object[]) null); //java.lang.IllegalArgumentException: object is not an instance of declaring class
System.out.println(" value in s is:"+s);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

最佳答案

你需要写

String s=(String) method.invoke(entity, (Object[]) null);

对于静态方法或应调用该方法的对象,Method.invoke 的第一个参数为 null。

关于java - 反射调用抛出 IllegalArgumentException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33008907/

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