Skip to content

CollectionFactory API is not type-safe [SPR-12537] #17142

@spring-projects-issues

Description

@spring-projects-issues

Sam Brannen opened SPR-12537 and commented

Status Quo

The changes made to CollectionFactory in conjunction with #15691 resulted in method signatures that are not type-safe, and the changes made in conjunction with #17089 further exacerbated the issue.

For example, the parameterized type E is not bound to the type of elements contained in the collection argument passed to createApproximateCollection(). Thus casting the value returned by EnumSet#copyOf(EnumSet) to (Collection<E>) can never guarantee that the returned collection actually contains elements of type E.


Example Tests

Each of the following tests (adapted from CollectionFactoryTests) compiles but throws a ClassCastException due to the lacking type safety of the method signatures.

@Test
public void createApproximateCollectionIsNotTypeSafeForEnumSet() {
	Collection<Integer> ints = createApproximateCollection(EnumSet.of(Color.BLUE), 3);
	ints.add(42);
}

@Test
public void createCollectionIsNotTypeSafeForEnumSet() {
	Collection<Integer> ints = createCollection(EnumSet.class, Color.class, 3);
	ints.add(42);
}

@Test
public void createApproximateMapIsNotTypeSafeForEnumMap() {
	EnumMap<Color, Integer> enumMap = new EnumMap<>(Color.class);
	enumMap.put(Color.RED, 1);
	enumMap.put(Color.BLUE, 2);
	Map<String, Integer> map = createApproximateMap(enumMap, 3);
	map.put("foo", 1);
}

@Test
public void createMapIsNotTypeSafeForEnumMap() {
	Map<String, Integer> map = createMap(EnumMap.class, Color.class, 3);
	map.put("foo", 1);
}

@Test
public void createMapIsNotTypeSafeForLinkedMultiValueMap() {
	Map<String, Integer> map = createMap(MultiValueMap.class, null, 3);
	map.put("foo", 1);
}

Deliverables

  1. Ensure that all methods in CollectionFactory are type-safe.
    • Consider reverting to raw types, or alternatively to Collection<Object> and Map<Object, Object> as was done by the Spring Data Team.
  2. Refactor CollectionFactoryTests accordingly.

Affects: 4.0 GA

Issue Links:

Metadata

Metadata

Assignees

Labels

in: coreIssues in core modules (aop, beans, core, context, expression)status: declinedA suggestion or change that we don't feel we should currently apply

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions