Skip to content

[java] Generalize UnnecessaryCast to flag all unnecessary casts #3218

@oowekyala

Description

@oowekyala

Is your feature request related to a problem? Please describe. UnnecessaryCast is artificially limited to casts on collection classes. These are quite rare post java 5. The rule has zero violations in the projects on which we regression test.

Describe the solution you'd like Make the rule report any cast that is unnecessary, finally making its behavior match its name.

This is what's implemented by #3204. The implementation strategy is the following. Given a cast that looks like this:

ContextType t = (CastType) expression;

, the cast is unnecessary if the type of expression is compatible (subtype, or subtype after boxing/unboxing/widening/unchecked conversions) with both CastType and ContextType. This ensures that the cast is not narrowing, and if removed, the code will still compile. The rule is not limited to assignment contexts like in the above example.

Examples:

import java.util.function.Function;
class SomeClass {
   static {
      Object o; long l; int i;

      o = (Object) new SomeClass(); // FN
      o = (Comparable<String>) "string"; // FN

      // primitive widening
      l = (long) 2;   // FN
      l = (Long) 2;   // FN
      l = (long) 2.0; // TN (narrowing cast)
      l = (byte) i;   // TN (narrowing cast)

      // boxing/unboxing casts (since java 5)

      o = (Integer) 3; // FN (autoboxing)
      o = (Long) 3;    // TN

      // casts that give a target type to a lambda/ method ref are necessary
      o = (Function<Integer, String>) Integer::toString; // TN
   }
}

Metadata

Metadata

Assignees

Labels

a:false-negativePMD doesn't flag a problematic piece of codean:enhancementAn improvement on existing features / rules

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions