ClassCastException when using AssignmentExpressionTreeImpl

Hello @rainyheart, and welcome on this forum.

When writting custom rules, you are never supposed to use any implementation classes from the SonarJava plugin. These classes are not exposed at runtime, and not available. See for instance this related thread:

Now, to get back to your rule. If you are trying to check if your ExpressionTree is an assignment, you should use the dedicated is(...) method of the Tree API, as introduced in the SonarJava tutorial for custom rules. You should rewrite your code to end up with something such as:

    private boolean hasSetFetchType(ExpressionTree et) {
        boolean result = false;
        if (et.is(Tree.Kind.ASSIGNMENT)) {
            // now you are sure that it's an assignment, you can cast directly to the interface
            AssignmentExpressionTree aet = (AssignmentExpressionTree) et;
            // searching on the variable side of the assignment
            if ("fetch".equalsIgnoreCase(aet.variable().firstToken().text())) {
                // searching on the expression side of theassignment
                String fetchType = aet.expression().lastToken().text();
                if ("LAZY".equalsIgnoreCase(fetchType.trim()) || "EAGER".equalsIgnoreCase(fetchType.trim())) {
                    result = true;
                }
            }
        }
        return result;
    }

Note that by relying only on first/last tokens, and therefore completely ignoring the AST structure, you will probably miss many uses cases, such as these ones, for instance:

fetch = ("LAZY"); 
fetch = "LAZY" + "";

I hope this helps.

Cheers,
Michael

1 Like