From f27bdcb737ed74b101b8bc82fda02bc9e9eaf84f Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Fri, 10 Jun 2016 17:06:45 -0700 Subject: [PATCH] Prevent APT crashes on older Java versions Update TypeUtils to guard against the use of older Java versions. Both `Collection` and `Map` type lookups now fallback to generic free versions of the classes. Prior to this commit using `xmlbeans-maven-plugin` in combination with Spring Boot's annotation processor could result in `IllegalArgumentException: Incorrect number of type arguments`. Fixes gh-6122 --- .../configurationprocessor/TypeUtils.java | 26 ++++++++++++++----- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeUtils.java b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeUtils.java index c4d625eeb3..59d02f551d 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeUtils.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeUtils.java @@ -27,7 +27,6 @@ import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; -import javax.lang.model.type.WildcardType; import javax.lang.model.util.Types; /** @@ -73,12 +72,25 @@ class TypeUtils { TypeUtils(ProcessingEnvironment env) { this.env = env; Types types = env.getTypeUtils(); - WildcardType wc = types.getWildcardType(null, null); - this.collectionType = types.getDeclaredType( - this.env.getElementUtils().getTypeElement(Collection.class.getName()), - wc); - this.mapType = types.getDeclaredType( - this.env.getElementUtils().getTypeElement(Map.class.getName()), wc, wc); + this.collectionType = getDeclaredType(types, Collection.class, 1); + this.mapType = getDeclaredType(types, Map.class, 2); + } + + private TypeMirror getDeclaredType(Types types, Class typeClass, + int numberOfTypeArgs) { + TypeMirror[] typeArgs = new TypeMirror[numberOfTypeArgs]; + for (int i = 0; i < typeArgs.length; i++) { + typeArgs[i] = types.getWildcardType(null, null); + } + TypeElement typeElement = this.env.getElementUtils() + .getTypeElement(typeClass.getName()); + try { + return types.getDeclaredType(typeElement, typeArgs); + } + catch (IllegalArgumentException ex) { + // Try again without generics for older Java versions + return types.getDeclaredType(typeElement); + } } public String getType(Element element) {