Skip to content

[java] UnnecessaryCast reports false-positive for ByteBuffer methods when targeting Java 8 #4620

@kohlschuetter

Description

@kohlschuetter

Affects PMD Version:
7.0.0-SNAPSHOT, 6.55.0

Rule:
UnnecessaryCast

Description:

Code Sample demonstrating the issue:

    ByteBuffer bb = ByteBuffer.allocate(5 * 4);
    return (byte[])bb.flip().array();

and

    public foo(ByteBuffer nativeAddress) {
        this.nativeAddress = nativeAddress == null ? null : (ByteBuffer) (Object) nativeAddress
        .duplicate().rewind();
    }

Expected outcome:

PMD reports a violation, but that's wrong. That's a false positive as long as Java 8 or lower is targeted.

Running PMD through: CLI, Maven

Trying to address these warnings results in the following Java compiler errors as long as Java 8 is targeted:

[ERROR] AFTIPCSocketAddress.java:[633,27] incompatible types: java.lang.Object cannot be converted to byte[]
and
[ERROR] AFSocketAddress.java:[127,28] incompatible types: bad type in conditional expression
[ERROR] java.nio.Buffer cannot be converted to java.nio.ByteBuffer

The problem is that prior to Java 9, several methods in ByteBuffer were not overridden to return a this of type ByteBuffer, so they return a Buffer only. Buffer itself returns this of type Buffer (naturally), and, surprisingly, Object for array().

Moreover, slapping @SuppressWarnings("cast") around the method does not calm PMD at all.

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positivePMD flags a piece of code that is not problematicin:type-resolutionAffects the type resolution code

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions