Skip to content

[java] ClassCastExceptionWithToArray can't detect the case that call toArray() in this.foo.toArray() #2535

@wuchiuwong

Description

@wuchiuwong

Affects PMD Version:
6.22.0
Rule:
ClassCastExceptionWithToArray

Description:
ClassCastExceptionWithToArray can't detect the case that call toArray() in this.foo.toArray(). This rule is implemented through xpath search:

//CastExpression[Type/ReferenceType/ClassOrInterfaceType[@Image !=
"Object"]]/PrimaryExpression
[
 PrimaryPrefix/Name[ends-with(@Image, '.toArray')]
 and
 PrimarySuffix/Arguments[count(*) = 0]
and
count(PrimarySuffix) = 1
]

AST analyse result of the code sample:

<PrimaryExpression FindBoundary='false' Image='' SingleLine='true'>
    <PrimaryPrefix FindBoundary='false' Image='' SingleLine='true' SuperModifier='false' ThisModifier='true' />
    <PrimarySuffix ArgumentCount='-1' Arguments='false' ArrayDereference='false' indBoundary='false' Image='labels' SingleLine='true' />
    <PrimarySuffix ArgumentCount='-1' Arguments='false' ArrayDereference='false' FindBoundary='false' Image='toArray' SingleLine='true' />
    <PrimarySuffix ArgumentCount='0' Arguments='true' ArrayDereference='false' FindBoundary='false' Image='' SingleLine='true'>
        <Arguments ArgumentCount='0' FindBoundary='false' Image='' SingleLine='true' Size='0' />
    </PrimarySuffix>
</PrimaryExpression>

In the case this.labels.toArray(), AST result is: PrimaryPrefix is '', and toArray is in PrimarySuffix

Code Sample demonstrating the issue:

(String[]) this.labels.toArray();

Expected outcome:
false-negative

Running PMD through:
CLI

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-negativePMD doesn't flag a problematic piece of code

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions