Skip to content

Commit 2c351ac

Browse files
jkschneiderclaude
andauthored
Fix NPE in IteratorNext recipe when iterator() has no explicit receiver (#796)
The recipe failed with a NullPointerException when encountering code like `iterator().next()` where the iterator() method is called without an explicit receiver (using implicit `this`). This fix adds a null check for `iteratorSelect` before attempting to check its type. Added test case to verify the recipe correctly handles implicit receiver cases without throwing NPE. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-authored-by: Claude <noreply@anthropic.com>
1 parent a2b5986 commit 2c351ac

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

src/main/java/org/openrewrite/java/migrate/util/IteratorNext.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
5959
if (NEXT_MATCHER.matches(nextInvocation) && ITERATOR_MATCHER.matches(nextInvocation.getSelect())) {
6060
J.MethodInvocation iteratorInvocation = (J.MethodInvocation) nextInvocation.getSelect();
6161
Expression iteratorSelect = iteratorInvocation.getSelect();
62-
if (TypeUtils.isAssignableTo("java.util.SequencedCollection", iteratorSelect.getType())) {
62+
if (iteratorSelect != null && TypeUtils.isAssignableTo("java.util.SequencedCollection", iteratorSelect.getType())) {
6363
JavaType.Method getFirst = iteratorInvocation.getMethodType().withName("getFirst");
6464
return iteratorInvocation
6565
.withName(iteratorInvocation.getName().withSimpleName("getFirst").withType(getFirst))

src/test/java/org/openrewrite/java/migrate/util/IteratorNextTest.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,4 +140,22 @@ void bar(List<String> collection) {
140140
)
141141
);
142142
}
143+
144+
@Test
145+
void implicitThisIteratorNextUnchanged() {
146+
rewriteRun(
147+
//language=java
148+
java(
149+
"""
150+
import java.util.*;
151+
152+
class Foo extends ArrayList<String> {
153+
void bar() {
154+
String first = iterator().next();
155+
}
156+
}
157+
"""
158+
)
159+
);
160+
}
143161
}

0 commit comments

Comments
 (0)