Compare an Object to a primitive type

Frontear :

I'd like to perform a safety check for my getClass().getField(...).set(...) where the value I am setting should match the type of that field, (int x = 1 should only allow Integers to be set). The problem is, I'm having a hard time finding ways to compare the two. Currently this is the code:

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);
}

I've tried a lot of things, and searched around the web for quite a bit, but cannot find an answer which solely focuses on this usage of it. I've tried things like field.getType().getClass().equals(newValue.getClass()), field.getType().equals(newValue), and more, and they do not work. How can I reasonably compare a primitive field.getType() to an Object value passed in, or, how would I, in this case, compare an int, to an Integer?

Sagar Gandhi :

Step 1 : Check field.isPrimitive(). If it returns true then it's a primitive type. and proceed to step 3.

Step 2: If it's not primitive then you can directly check field.getType() == newValue.getClass() and then set the value

Step 3: if it's primitive then you need to have a static map

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=92222&siteId=1