Java reflection and autoboxing

I use reflection to set the value of the field, but when I try to assign Short to short, I get an error because isAssignable () returns false.

private void setFieldValue(Object result, Field curField, Object value) throws NoSuchFieldException, IllegalAccessException {
    if (!curField.getType().isAssignableFrom(value.getClass())) {
        LOG.error("Can't set field value type mismatch: field class: " + curField.getType().getSimpleName() + ", value class: " + value.getClass().getSimpleName());
    } else {
        curField.set(result, value);
    }
}

any hints how can i do a reflection for auto boxing?

+4
source share
3 answers

The box int getTypewill be returned int.class. This was so, since before the auto-box was introduced in Java, and therefore, correctly, if you maintain backward compatibility, it Class.isAssignableFrom(Class)returns falsewhen the type of an object is passed by a primitive type.

Or as in your case:

int.class.isAssignableFrom(int.class)

will return true, but:

int.class.isAssignableFrom(Integer.class)

will return false.

, , , Jakarta Commons (ClassUtils.isAssignable(, , )).

+2

, , , , . , lib, @Danny.

0

, ( ) (# isPrimitive()). , . , , , - . , 8 , .

0
source

Source: https://habr.com/ru/post/1532686/


All Articles