Skip to content

Commit d72aeac

Browse files
committed
Create well-known non-interface types without using reflection
Closes gh-28718
1 parent 5247eeb commit d72aeac

File tree

1 file changed

+14
-15
lines changed

1 file changed

+14
-15
lines changed

spring-core/src/main/java/org/springframework/core/CollectionFactory.java

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2021 the original author or authors.
2+
* Copyright 2002-2022 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -181,27 +181,26 @@ public static <E> Collection<E> createCollection(Class<?> collectionType, int ca
181181
@SuppressWarnings({"unchecked", "cast"})
182182
public static <E> Collection<E> createCollection(Class<?> collectionType, @Nullable Class<?> elementType, int capacity) {
183183
Assert.notNull(collectionType, "Collection type must not be null");
184-
if (collectionType.isInterface()) {
185-
if (Set.class == collectionType || Collection.class == collectionType) {
186-
return new LinkedHashSet<>(capacity);
187-
}
188-
else if (List.class == collectionType) {
189-
return new ArrayList<>(capacity);
190-
}
191-
else if (SortedSet.class == collectionType || NavigableSet.class == collectionType) {
192-
return new TreeSet<>();
193-
}
194-
else {
195-
throw new IllegalArgumentException("Unsupported Collection interface: " + collectionType.getName());
196-
}
184+
if (LinkedHashSet.class == collectionType || HashSet.class == collectionType ||
185+
Set.class == collectionType || Collection.class == collectionType) {
186+
return new LinkedHashSet<>(capacity);
187+
}
188+
else if (ArrayList.class == collectionType || List.class == collectionType) {
189+
return new ArrayList<>(capacity);
190+
}
191+
else if (LinkedList.class == collectionType) {
192+
return new LinkedList<>();
193+
}
194+
else if (SortedSet.class == collectionType || NavigableSet.class == collectionType) {
195+
return new TreeSet<>();
197196
}
198197
else if (EnumSet.class.isAssignableFrom(collectionType)) {
199198
Assert.notNull(elementType, "Cannot create EnumSet for unknown element type");
200199
// Cast is necessary for compilation in Eclipse 4.4.1.
201200
return (Collection<E>) EnumSet.noneOf(asEnumType(elementType));
202201
}
203202
else {
204-
if (!Collection.class.isAssignableFrom(collectionType)) {
203+
if (collectionType.isInterface() || !Collection.class.isAssignableFrom(collectionType)) {
205204
throw new IllegalArgumentException("Unsupported Collection type: " + collectionType.getName());
206205
}
207206
try {

0 commit comments

Comments
 (0)