Domanda

I'm using reflection to set field value but when I try to assign Short to short I get error because isAssignable() return 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 clues how can I make reflection to do autoboxing?

È stato utile?

Soluzione

For an int field getType will return int.class. This has been the case since before auto- boxing was introduced to Java and so, correctly, if you're preserving backward compatibility, Class.isAssignableFrom(Class) returns false when the object type is passed the primitive type.

Or as in your case:

int.class.isAssignableFrom(int.class)

would return true, while:

int.class.isAssignableFrom(Integer.class)

would return false.

The quick fix it to write a method that when presented with the object type, checks for the that type and the primitive or use the classes in libraries like Jakarta Commons (ClassUtils.isAssignable(Class, Class, boolean)).

Altri suggerimenti

You'll need to manually check for whether the value is possibly a wrapper for a primitive type, and make special cases for all the primitive types. Sounds like a pain, use a lib as @Danny suggested.

Simply check if one (and only one) class is a primitive (Class#isPrimitive()). If yes check for autoboxing use a switch. Since there is no subclassing involved, you can just write a helper method where the primitive class is first and the other second. This way it is just 8 comparisons for compensating so you will not need an additional dependency.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top