Skip to content

Hint "Remove unused variable" is incorrectly offered for loop variable of enhanced for loop #9198

@nmatt

Description

@nmatt

Apache NetBeans version

Apache NetBeans 28

What happened

In an enhanced for loop with an empty body (or an otherwise seemingly unused loop variable), the hint 'Remove unused "variable"' is offered. When selecting the hint, an Unexpected Exception occurs: java.lang.ClassCastException: class com.sun.tools.javac.tree.JCTree$JCBlock cannot be cast to class com.sun.source.tree.VariableTree.

While selecting the hint obviously doesn't make much sense, it can happen by accident when wanting to select another hint on the for loop, for example 'Change type of variable to correct type' when the loop variable type doesn't match the iterable expression type. Not offering the nonsensical "Remove unused variable" hint in the first place would help prevent selecting the wrong hint.

Language / Project Type / NetBeans Component

Java, Hints

How to reproduce

With the following code in Java statement context:

for (int key : System.getenv().keySet()) { }

Both 'Remove unused "key"' and 'Change type of key to String' are offered. Selecting the former causes the Unexpected Exception.

Did this work correctly in an earlier version?

No / Don't know

Operating System

Windows

JDK

17

Apache NetBeans packaging

Apache NetBeans binary zip

Anything else

No response

Are you willing to submit a pull request?

No

Metadata

Metadata

Assignees

No one assigned

    Labels

    kind:bugBug report or fixneeds:triageRequires attention from one of the committers

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions