Skip to content

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

Closed

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.

Activity

  1. added
    a:false-positive
    on Jul 2, 2023
  2. changed the title [-][java] [/-] [+][java] UnnecessaryCast reports false-positive for ByteBuffer methods when targeting Java 8[/+] on Jul 2, 2023
  3. oowekyala commented on Jul 2, 2023

    @oowekyala
    Member

    This is down to the auxclasspath configuration. If you haven't added the JDK libraries to the auxclasspath, PMD uses the one on its boot classpath. This means if you run PMD with eg a Java 17 JVM, it will see the JDK 17 standard lib, not the Java 8 one.

    While investigating this I realized that the classloader we use for the auxclasspath is actually parent first, so configuring the auxclasspath to include the java 8 rt.jar does not work as expected. We need to change that to child first. In the meantime you can run PMD with a java 8 VM to avoid these warnings.

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

    Ref #1900

  4. kohlschuetter commented on Jul 2, 2023

    @kohlschuetter
    Author

    Thanks for the clarification!

    Running with JDK 8 is unfortunately harder than one may think, because then module-info.java will not be parsed correctly.

    Additionally, when running from within Maven, one would have to specify <jdkToolchain><version>1.8</version></jdkToolchain>, however that requires setting up .m2/toolchain.xml accordingly. That is not really portable in the context of an open source project, at least not without further setup steps.

    Can PMD perhaps hard-code some of these rules for backwards compatibility?
    Definitely fixing #1900 seems the way to go here, because we already suppressed this warning for exactly that backwards compatibility issue.

  5. adangel commented on Jul 6, 2023

    @adangel
    Member

    Running with JDK 8 is unfortunately harder than one may think, because then module-info.java will not be parsed correctly.

    Not sure, I understand this. If you targeting Java 8 in your project, then why do you have a module-info.java?

    I assume, the open source project you are working on is https://github.com/kohlschutter/junixsocket where you had this problem. In that case, it's much more complex because of multi release: You actually have some code directories, which contain java8 and others which contain code for other java versions - that means, your project has not a single targetJdk but multiple different ones (from the perspective of PMD).

    In theory (not sure if this is actually feasible) you would need to run PMD multiple times with the correct combination of source directories, auxclasspath, targetJdk setting and using the correct java runtime.

    The setting targetJdk for the maven-pmd-plugin actually only sets the source version - and our parser would complain if it sees a language construct for a newer version. But it doesn't control the java classes, that are loaded for type resolution. All the classes for type resolution are loaded from the auxclasspath. The maven-pmd-plugin configures the auxclasspath automatically (based on the dependencies of the project), but I don't remember adding any JDK path on there. So it basically still relies on the "parent first" class loading behavior - meaning the Java runtime used to run maven (or if using toolchains, that one).

  6. added
    in:type-resolution
    on Jul 6, 2023
  7. kohlschuetter commented on Jul 6, 2023

    @kohlschuetter
    Author

    Indeed I'm seeing these PMD issues with junixsocket.

    The code in junixsocket ends up in a multi-release jar to support all Java versions beginning with Java 8.

    The codebase is structured in a way that allows forward-compatible development in Eclipse.
    The "default" Java code is under src/main/java. If there is some code that will not work with an older version (typically Java 8), then there is a copy of that class source file in src/main/javaX (with X being 8, 9, 10, etc.)

    At build time, we compile all classes for all supported versions and copy the corresponding class files into a META-INF/versions/X directory for all Java versions starting with 9 (the Java 8 classes land in the base directory). Even if there is no difference in the source, we can leverage compiler improvements such as avoiding accessor class generation with Java 11+, etc.

    We check the main code with PMD using a targetJdk of 8 since the language itself is supposed to be forward-compatible (with certain exceptions that can be dealt with). Indeed, we therefore end up with a module-info.java file that is surfaced by PMD with a targetJdk level of 8 (which we don't compile with Java 8, however).

    Yes, we could run PMD for all Java versions but that may be overkill (and would still generate false-positive errors). What we kind of need is a targetJdk value of multirelease-8+, i.e., a lenient processor that understands all modern Java code but wouldn't show certain errors for very specific changes in the Java SDK. I believe there are only a few cases like this that would cause false-positive PMD errors in a multi-release environment (e.g., the Object->byte[], Buffer->ByteBuffer API change, or the AutoCloseable addition for ExecutorService in Java 19).

  8. kohlschuetter commented on Nov 10, 2023

    @kohlschuetter
    Author

    For what it's worth, I added a // NOPMD line to no avail.

    If parsing fails for whatever reason, at least that comment should be honored. I'm also happy if I'd have to move the comment to the first line if that would make the fix easier.

  9. jsotuyod commented on Nov 13, 2023

    @jsotuyod
    Member

    @kohlschuetter with #4621 already merged, completely fixing this is now pending on finalizing #4628.

    In the meantime, ensure you are adding the // NOPMD line at the same line that is being reported (which may not be the exact line where the cast is on multi-line statements).

    #1900 is not targeted for PMD 7.0.0, but is definitely in the backlog. Contributions to push it forward are always welcomed.

  10. added
    needs:pmd7-revalidation
    and removed
    needs:pmd7-revalidation
    on Mar 17, 2024
  11. jsotuyod commented on Apr 28, 2024

    @jsotuyod
    Member

    With #4628 being included in PMD 7.0.0, setting up the proper Java runtime in the auxclasspath is possible and should avoid these issues.

  12. modified the milestones: 7.2.0, 7.0.0 on Apr 28, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positivein:type-resolution

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions