记 java.lang.IllegalArgumentException: object is not an instance of declaring class
本来想通过反射获取某个List对象中指定属性的值。根据网上很多答案遇到了上面的问题!
贴代码:
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import io.github.vforjuvenile.propertiesEditor.Person;
public class ListTest {
public static void main(String[] args) throws Exception {
Person p = new Person();
p.setAge(20);
Person p1 = new Person();
p1.setAge(25);
List<Person> list = new ArrayList<Person>() ;
list.add(p);
list.add(p1);
sumList(list,"age");
}
private static int sumList(List<?> list,String attribute) {
try {
for (Iterator<?> iterator = list.iterator(); iterator.hasNext();) {
Object object = iterator.next();
Class<?> clazz = object.getClass();
// Field field = clazz.getDeclaredField(attribute);
// System.out.println(field);
attribute = attribute.substring(0, 1).toUpperCase() + attribute.substring(1);//拼接获取属性get方法的名字
// Method m = clazz.getMethod("get" + attribute);//获取get方法
Method m = clazz.getDeclaredMethod("get" + attribute);//获取get方法
System.out.println(clazz.getName());
Object result = m.invoke(clazz);//获取属性值(这步报错)
System.out.println(result);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
}
看了很多资料,根据报错发现,m.invoke();方法里应该穿的是对象,而不应该是类,应该改为:
Object result = m.invoke(object);
即 iterator.next();
获取的对象!