From 8e85f01660789f4b6b7a595fa9a93791ab47c6d5 Mon Sep 17 00:00:00 2001 From: Jacob van Lingen Date: Sat, 22 Feb 2025 15:17:37 +0100 Subject: [PATCH] Put the `getCommentTree` reflection code back in (#5089) --- .../java/isolated/ReloadableJava17ParserVisitor.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/rewrite-java-17/src/main/java/org/openrewrite/java/isolated/ReloadableJava17ParserVisitor.java b/rewrite-java-17/src/main/java/org/openrewrite/java/isolated/ReloadableJava17ParserVisitor.java index 549181ac893..57cb58c2383 100644 --- a/rewrite-java-17/src/main/java/org/openrewrite/java/isolated/ReloadableJava17ParserVisitor.java +++ b/rewrite-java-17/src/main/java/org/openrewrite/java/isolated/ReloadableJava17ParserVisitor.java @@ -46,6 +46,8 @@ import javax.lang.model.element.Modifier; import javax.lang.model.element.Name; import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.*; @@ -1744,9 +1746,15 @@ public J visitWildcard(WildcardTree node, Space fmt) { // The spacing of initialized enums such as `ONE (1)` is handled in the `visitNewClass` method, so set it explicitly to “” here. String prefix = isEnum(t) ? "" : source.substring(cursor, indexOfNextNonWhitespace(cursor, source)); cursor += prefix.length(); - Space p = formatWithCommentTree(prefix, (JCTree) t, docCommentTable.getCommentTree((JCTree) t)); - @SuppressWarnings("unchecked") J2 j = (J2) scan(t, p); + // Java 21 and 23 have a different return type from getCommentTree; with reflection we can support both + // Though this is the Java 17 parser, we still need to support it if people use this parser with newer Java versions (e.g. https://github.com/PicnicSupermarket/error-prone-support/pull/1557) + Method getCommentTreeMethod = DocCommentTable.class.getMethod("getCommentTree", JCTree.class); + DocCommentTree commentTree = (DocCommentTree) getCommentTreeMethod.invoke(docCommentTable, t); + @SuppressWarnings("unchecked") J2 j = (J2) scan(t, formatWithCommentTree(prefix, (JCTree) t, commentTree)); return j; + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { + reportJavaParsingException(ex); + throw new IllegalStateException("Failed to invoke getCommentTree method", ex); } catch (Throwable ex) { reportJavaParsingException(ex); throw ex;