문제

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?

도움이 되었습니까?

해결책

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)).

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top