+-

我想对我的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进行比较?
最佳答案
步骤1 :
检查field.isPrimitive().如果它返回true,则它是原始类型.然后继续第3步.
检查field.isPrimitive().如果它返回true,则它是原始类型.然后继续第3步.
第2步:
如果它不是原始的那么你可以直接检查
field.getType()== newValue.getClass()然后设置值
第3步:
如果它是原始的那么你需要一个静态地图
public final static Map<Class<?>, Class<?>> map = new HashMap<Class<?>, Class<?>>();
static {
map.put(boolean.class, Boolean.class);
map.put(byte.class, Byte.class);
map.put(short.class, Short.class);
map.put(char.class, Character.class);
map.put(int.class, Integer.class);
map.put(long.class, Long.class);
map.put(float.class, Float.class);
map.put(double.class, Double.class);
}
Class<?> clazz = map.get(field.getType());
then check clazz == newValue.getClass() and then set the variable.
点击查看更多相关文章
转载注明原文:java – 将Object与基本类型进行比较 - 乐贴网