我希望对我的getClass().getField(...).set(...)
进行安全检查,设置的值应该与该字段的类型匹配(例如int x = 1只允许设置整数)。问题是,我很难找到比较两者的方法。目前这是代码:
int foo = 14;
Field field = getClass().getDeclaredField("foo");
Object source = this;
// make the field accessible...
public void safeSet(Object newValue) throws IllegalAccessException {
// compare the field.getType() to the newValue type
field.set(source, newValue);
}
我尝试了很多方法,并在网上搜索了一段时间,但找不到一个仅关注此用法的答案。我尝试过像
field.getType().getClass().equals(newValue.getClass())
、field.getType().equals(newValue)
等方法,但都无法正常工作。在这种情况下,如何合理地比较原始的field.getType()和传入的对象值,或者如何比较int
和Integer
?
getClass().getField("...")
,要么使用Xxx.class.getDeclaredField("...")
来处理子类。 - Joop Eggennull
,因此总会有一个旧值,其包装表示必须与包装的新值具有相同的类型。当您不想读取字段时,请查看如何获取类型的默认值… - Holger