今天在使用反射时出现报错
Exception in thread "main" java.lang.IllegalArgumentException: Can not set java.lang.Integer field Person.age to (int)10
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:191)
at sun.reflect.UnsafeObjectFieldAccessorImpl.setInt(UnsafeObjectFieldAccessorImpl.java:114)
at java.lang.reflect.Field.setInt(Field.java:949)
at Test.main(Test.java:19)
发现使用setInt设置Integer时出现错误,记录一下。
总结:
在设置基础数据类型的包装类时要使用set(Object obj, Object value)来设置值
测试
Person.java
@Getter
@Setter
@Data
public class Person {
private Date date;
int cs;
}
public static void main(String[] args) throws IllegalAccessException, InstantiationException {
Class<Person> personClass = Person.class;
Person person = personClass.newInstance();
Field[] declaredFields = personClass.getDeclaredFields();
for (Field declaredField : declaredFields) {
String typeName = declaredField.getGenericType().getTypeName();
declaredField.setAccessible(true);
System.out.println(typeName);
if (typeName.contains("int")) {
declaredField.setInt(person, 10);
declaredField.set(person, 10);
}
if (typeName.contains("Integer")) {
// declaredField.setInt(person, 10);
declaredField.set(person, 10);
}
}
}