From d72aeac319e1f98018acf41f2c1c185e9e0652b8 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 13 Jul 2022 11:09:43 +0200 Subject: [PATCH] Create well-known non-interface types without using reflection Closes gh-28718 --- .../core/CollectionFactory.java | 29 +++++++++---------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/core/CollectionFactory.java b/spring-core/src/main/java/org/springframework/core/CollectionFactory.java index 4f90a3bff1..15e3ee7753 100644 --- a/spring-core/src/main/java/org/springframework/core/CollectionFactory.java +++ b/spring-core/src/main/java/org/springframework/core/CollectionFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -181,19 +181,18 @@ public final class CollectionFactory { @SuppressWarnings({"unchecked", "cast"}) public static Collection createCollection(Class collectionType, @Nullable Class elementType, int capacity) { Assert.notNull(collectionType, "Collection type must not be null"); - if (collectionType.isInterface()) { - if (Set.class == collectionType || Collection.class == collectionType) { - return new LinkedHashSet<>(capacity); - } - else if (List.class == collectionType) { - return new ArrayList<>(capacity); - } - else if (SortedSet.class == collectionType || NavigableSet.class == collectionType) { - return new TreeSet<>(); - } - else { - throw new IllegalArgumentException("Unsupported Collection interface: " + collectionType.getName()); - } + if (LinkedHashSet.class == collectionType || HashSet.class == collectionType || + Set.class == collectionType || Collection.class == collectionType) { + return new LinkedHashSet<>(capacity); + } + else if (ArrayList.class == collectionType || List.class == collectionType) { + return new ArrayList<>(capacity); + } + else if (LinkedList.class == collectionType) { + return new LinkedList<>(); + } + else if (SortedSet.class == collectionType || NavigableSet.class == collectionType) { + return new TreeSet<>(); } else if (EnumSet.class.isAssignableFrom(collectionType)) { Assert.notNull(elementType, "Cannot create EnumSet for unknown element type"); @@ -201,7 +200,7 @@ public final class CollectionFactory { return (Collection) EnumSet.noneOf(asEnumType(elementType)); } else { - if (!Collection.class.isAssignableFrom(collectionType)) { + if (collectionType.isInterface() || !Collection.class.isAssignableFrom(collectionType)) { throw new IllegalArgumentException("Unsupported Collection type: " + collectionType.getName()); } try {