diff --git a/core/src/main/java/com/google/errorprone/refaster/UEnhancedForLoop.java b/core/src/main/java/com/google/errorprone/refaster/UEnhancedForLoop.java index 386cb8718c3..803a322dda6 100644 --- a/core/src/main/java/com/google/errorprone/refaster/UEnhancedForLoop.java +++ b/core/src/main/java/com/google/errorprone/refaster/UEnhancedForLoop.java @@ -24,8 +24,12 @@ import com.sun.source.tree.EnhancedForLoopTree; import com.sun.source.tree.Tree; import com.sun.source.tree.TreeVisitor; +import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCEnhancedForLoop; -import java.lang.reflect.InvocationTargetException; +import com.sun.tools.javac.tree.JCTree.JCExpression; +import com.sun.tools.javac.tree.JCTree.JCStatement; +import com.sun.tools.javac.tree.JCTree.JCVariableDecl; +import com.sun.tools.javac.tree.TreeMaker; import java.util.Arrays; /** @@ -122,12 +126,31 @@ public Kind getKind() { @Override public JCEnhancedForLoop inline(Inliner inliner) throws CouldNotResolveImportException { - return inliner - .maker() - .ForeachLoop( - getVariable().inline(inliner), - getExpression().inline(inliner), - getStatement().inline(inliner)); + return makeForeachLoop( + inliner.maker(), + getVariable().inline(inliner), + getExpression().inline(inliner), + getStatement().inline(inliner)); + } + + private static JCEnhancedForLoop makeForeachLoop( + TreeMaker maker, JCVariableDecl variable, JCExpression expression, JCStatement statement) { + try { + if (RuntimeVersion.isAtLeast20()) { + return (JCEnhancedForLoop) + TreeMaker.class + .getMethod("ForeachLoop", JCTree.class, JCExpression.class, JCStatement.class) + .invoke(maker, variable, expression, statement); + } else { + return (JCEnhancedForLoop) + TreeMaker.class + .getMethod( + "ForeachLoop", JCVariableDecl.class, JCExpression.class, JCStatement.class) + .invoke(maker, variable, expression, statement); + } + } catch (ReflectiveOperationException e) { + throw new LinkageError(e.getMessage(), e); + } } @Override