Frontear:
私はのための安全性チェックを実行したいのですが、私getClass().getField(...).set(...)
、私はそのフィールドの型と一致する必要があります設定していた値、(int型は、x = 1整数だけを設定することができるはずです)。問題は、私は2つを比較する方法を見つけることに苦労を抱えている、です。現在、このコードは次のとおりです。
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
?
サーガルガンジー:
ステップ1:チェック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.