From 20421355f2a5aeedeecda50aa367d2dfe93c5bf6 Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Sun, 6 Oct 2024 13:55:17 +0200 Subject: [PATCH] Use reflection to invoke getCommentTree to support Java 21 & 23 Fixes https://github.com/openrewrite/rewrite/issues/4540 --- .../java/isolated/ReloadableJava21ParserVisitor.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/rewrite-java-21/src/main/java/org/openrewrite/java/isolated/ReloadableJava21ParserVisitor.java b/rewrite-java-21/src/main/java/org/openrewrite/java/isolated/ReloadableJava21ParserVisitor.java index 2c59e8f8924..7ab8b5b26e2 100644 --- a/rewrite-java-21/src/main/java/org/openrewrite/java/isolated/ReloadableJava21ParserVisitor.java +++ b/rewrite-java-21/src/main/java/org/openrewrite/java/isolated/ReloadableJava21ParserVisitor.java @@ -44,6 +44,7 @@ import javax.lang.model.element.Modifier; import javax.lang.model.element.Name; import java.lang.reflect.Field; +import java.lang.reflect.Method; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.*; @@ -1664,7 +1665,10 @@ private J2 convert(Tree t) { try { String prefix = source.substring(cursor, max(((JCTree) t).getStartPosition(), cursor)); cursor += prefix.length(); - @SuppressWarnings("unchecked") J2 j = (J2) scan(t, formatWithCommentTree(prefix, (JCTree) t, docCommentTable.getCommentTree((JCTree) t))); + // Java 21 and 23 have a different return type from getCommentTree; with reflection we can support both + Method getCommentTreeMethod = DocCommentTable.class.getMethod("getCommentTree", JCTree.class); + DocCommentTree commentTree = (DocCommentTree) getCommentTreeMethod.invoke(docCommentTable, (JCTree) t); + @SuppressWarnings("unchecked") J2 j = (J2) scan(t, formatWithCommentTree(prefix, (JCTree) t, commentTree)); return j; } catch (Throwable ex) { // this SHOULD never happen, but is here simply as a diagnostic measure in the event of unexpected exceptions