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.
Affects PMD Version:
7.0.0-SNAPSHOT, 6.55.0
Rule:
UnnecessaryCast
Description:
Code Sample demonstrating the issue:
and
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
ByteBufferwere not overridden to return athisof typeByteBuffer, so they return aBufferonly.Bufferitself returnsthisof typeBuffer(naturally), and, surprisingly,Objectforarray().Moreover, slapping
@SuppressWarnings("cast")around the method does not calm PMD at all.