将对象与原始类型进行比较
Compare an Object to a primitive type
我想为我的 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
?[=16 进行比较=]
第 1 步:
检查 field.isPrimitive()
。如果它 returns 为真那么它就是原始类型。并继续第 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.
因为您想为字段赋值,所以这是执行此操作的内置解决方案。
if (getClass().getDeclaredField("foo").getType().isAssignableFrom(newValue.getClass())) {
....
}
它也适用于原始类型。
我想为我的 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
?[=16 进行比较=]
第 1 步:
检查 field.isPrimitive()
。如果它 returns 为真那么它就是原始类型。并继续第 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.
因为您想为字段赋值,所以这是执行此操作的内置解决方案。
if (getClass().getDeclaredField("foo").getType().isAssignableFrom(newValue.getClass())) {
....
}
它也适用于原始类型。