【发布时间】:2019-05-28 20:58:01
【问题描述】:
我想对我的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() 与传入的 Object 值进行比较,或者,在这种情况下,我将如何将 int 与 Integer 进行比较?
【问题讨论】:
-
Java 中确实缺少原始类型与其包装类的关联。一句话:
getClass().getField("...")或Xxx.class.getDeclaredField("...")处理子类。 -
if(field.getType().isPrimitive() && field.get(source).getClass() != newValue.getClass()) /* error */。因为原始值永远不可能是null,所以工作,因此,总是有一个旧值,其包装表示必须与包装的新值具有相同的类型。当您不想阅读该字段时,请查看how to get the default value for a type...
标签: java reflection types primitive