Skip to content

TypeUtils.isAssignable should return true for ParametrizedType assignable to Object [SPR-5390] #10063

Closed
@spring-projects-issues

Description

@spring-projects-issues

Vincent De Rijcke opened SPR-5390 and commented

isAssignable( Object.class, /* parametrizedtype or genericarraytype */ ) should be true

Test case:
public class SpringTypeUtilsTest {
private static final List<Long> LIST_LONG = null;
private static final List<Long>[] LIST_LONG_ARRAY = null;

private Type getFieldType(String fieldName) {
    try {
        return SpringTypeUtilsTest.class.getDeclaredField(fieldName).getGenericType();
    } catch (NoSuchFieldException e) {
        throw new RuntimeException("Field does not exist", e);
    }
}

@Test
public void testParametrizedTypeAssignableToObject() {
    Object o = (List<Long>) null;  // fine in java - so assignable should return true 
    
    assertTrue(TypeUtils.isAssignable(Object.class, getFieldType("LIST_LONG")));
}

@Test
public void testGenericArrayTypeAssignableToObject() {
    // Note that java use a GenericArrayType for an Array used as a Wildcard boundaries or ParametrizedTypeArgument,
   // instead of using the Array class object
    Object o = (List<Long>[]) null;  // fine in java - so assignable should return true 
    
    assertTrue(TypeUtils.isAssignable(Object.class, getFieldType("LIST_LONG_ARRAY")));
}

}

Proposed fix of TypeUtils.java:

//UPDATE isAssignable(Type lhsType, Type rhsType)
public static boolean isAssignable(Type lhsType, Type rhsType) {
if (lhsType == null) {
throw new IllegalArgumentException("Left-hand side type must not be null");
}
if (rhsType == null) {
throw new IllegalArgumentException("Right-hand side type must not be null");
}

if (lhsType.equals(rhsType)) {
    return true;
}
if (lhsType instanceof Class && rhsType instanceof Class) {
    return isAssignable((Class<?>) lhsType, (Class<?>) rhsType);
}

// ADDED
if (lhsType == Object.class && ( rhsType instanceof ParameterizedType || rhsType instanceof GenericArrayType)) {
return true;
}
// END ADDED
if (lhsType instanceof ParameterizedType && rhsType instanceof ParameterizedType) {
return isAssignable((ParameterizedType) lhsType, (ParameterizedType) rhsType);
}
if (lhsType instanceof WildcardType) {
return isAssignable((WildcardType) lhsType, rhsType);
}
return false;
}


Affects: 2.5.6, 3.0 M1

Metadata

Metadata

Assignees

Labels

in: coreIssues in core modules (aop, beans, core, context, expression)type: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions